﻿using CAPTS_Suite;
using MaterialSkin;
using MaterialSkin.Controls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolBar;
using System.IO;
using NPOI.SS.UserModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.IO.Ports;
using System.Drawing.Text;
using NPOI.POIFS.NIO;
using System.Windows.Forms.DataVisualization.Charting;
using NPOI.POIFS.Crypt.Dsig;
using System.Collections;
using System.Diagnostics;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using preprocess;
using NPOI.XSSF.Streaming.Values;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Linq.Expressions;
using TencentCloudExamples;
using System.Reflection.Emit;
using Org.BouncyCastle.Asn1.X509;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;

namespace CAPTS
{
    public partial class Form1 : MaterialForm
    {
        private readonly MaterialSkinManager materialSkinManager;
        private CancellationTokenSource cts; // 光照取消令牌
        CAPTS_Borker CAPTS_Borker1;
        Thread RunMearLoop;
        public static string serial_test_dis;
        public static string state;
        List<double> data_CO2 = new List<double>();
        List<double> data_H2O = new List<double>();
        List<double> data_CH4 = new List<double>();
        List<double> data_N2O = new List<double>();
        List<double> data_NH3 = new List<double>();
        List<double> data_Ac = new List<double>();
        List<double> data_EC = new List<double>();
        List<double> data_MER = new List<double>();
        List<double> data_N2OER = new List<double>();
        List<double> data_NH3ER = new List<double>();
        List<DateTime> full_time = new List<DateTime>();
        String previousCaseIndex = "1";//测量箱序号初始为1
        static OneMeasurementData omd_4 = new OneMeasurementData(16);
        static List<OneChamber> chamberList_4= new List<OneChamber>();
        public static Dictionary<string, Dictionary<string, string[]>> Fit_Data { get; set; } = new Dictionary<string, Dictionary<string, string[]>>();
        public static DateTime slope_time;
        string Items_Slope;
        int combox_selectedIndex;
        string[] tb46;
        double CO2_slope, CO2_intercept, H2O_slope, H2O_intercept, CH4_slope, CH4_intercept, N2O_slope, N2O_intercept, NH3_slope, NH3_intercept;
        string NoDry,NoDry1;
        bool Dryis_open=true;
        int stop_time;
        int progress;
        OneChamber om = new OneChamber();
        Task t3;
        Task t4;
        public static String Device_Flag = "3";//设备标记:“1”为LI-COR，“2”为PICARRO，默认为Picarro
        bool connect_flag = false; //用来约束连接串口只执行一次
        public static bool isStoppedByUser = false;//判断是用户点击停止按钮还是单片机断电
        bool isStartByUser = false;//判断用户是否点击开始
        public static DateTime lastDataReceivedTime; // 记录上次接收到数据的时间
        //private System.Windows.Forms.Timer dataReceiveTimer; // 定义dataReceiveTimer变量
        private System.Windows.Forms.Timer Power_off_Timer; //定时开关机
        private System.Windows.Forms.Timer close_pump; //干燥气路时关闭气泵
        bool slave_stop=false;
        public static bool Is_Customize = false;
        string time_start;
        string time_stop;
        string[] Master_array;//1-16
        string[] Slave_array;//17-32
        string[][] data_chart = new string[][]
        {
            new []{ "CO₂：", "0","ppm"},
            new []{ "H₂O：", "0","ppt" },
            new []{ "CH₄：", "0","ppb"},
            new []{ "N₂O：", "0","ppb"},
            new []{ "NH₃：", "0","ppb"},
            new []{"Temp ：", "0","℃"},
            new []{ "RH：", "0","%"},
            new []{ "PPFD:", "0","µmol/m²s"},
            new []{ "PA：", "0","KPa"},
        };
        float light_a;
        float light_b;
        float light_c;
        float light_d;
        int light_max;
        bool Debug_Button = false;
        public Form1()
        {
            InitializeComponent();

            // Initialize MaterialSkinManager
            materialSkinManager = MaterialSkinManager.Instance;

            // Set this to false to disable backcolor enforcing on non-materialSkin components
            // This HAS to be set before the AddFormToManage()
            materialSkinManager.EnforceBackcolorOnAllComponents = true;

            // MaterialSkinManager properties
            materialSkinManager.AddFormToManage(this);
            materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;

            materialSkinManager.ColorScheme = new ColorScheme(Primary.Green600,Primary.Green700,Primary.Green200,Accent.Red100,TextShade.WHITE);

            materialListBoxFormStyle.Clear();
            foreach (var FormStyleItem in Enum.GetNames(typeof(MaterialForm.FormStyles)))
            {
                materialListBoxFormStyle.AddItem(FormStyleItem);
                if (FormStyleItem == this.FormStyle.ToString()) materialListBoxFormStyle.SelectedIndex = materialListBoxFormStyle.Items.Count-4;
            }

            // 设置默认选择项为 ActionBar_40
            materialListBoxFormStyle.SelectedIndex = materialListBoxFormStyle.Items.Count-4;

            // 设置事件处理程序
            materialListBoxFormStyle.SelectedIndexChanged += (sender, args) =>
            {
                MaterialForm.FormStyles SelectedStyle = (MaterialForm.FormStyles)Enum.Parse(typeof(MaterialForm.FormStyles), args.Text);
                if (this.FormStyle != SelectedStyle) this.FormStyle = SelectedStyle;
            };

            // 确保表单样式也设置为默认的 ActionBar_40
            this.FormStyle = MaterialForm.FormStyles.ActionBar_40;
            DrawerAutoShow = false;

        }



        private void materialButton1_Click(object sender, EventArgs e)
        {
            materialSkinManager.Theme = materialSkinManager.Theme == MaterialSkinManager.Themes.DARK ? MaterialSkinManager.Themes.LIGHT : MaterialSkinManager.Themes.DARK;
            updateColor();
        }

        private int colorSchemeIndex;

        private void MaterialButton1_Click(object sender, EventArgs e)
        {
            colorSchemeIndex++;
            if (colorSchemeIndex > 2)
                colorSchemeIndex = 0;
            updateColor();
        }

        private void updateColor()
        {
            //These are just example color schemes
            switch (colorSchemeIndex)
            {
                case 0:
                    materialSkinManager.ColorScheme = new ColorScheme(
                        Primary.Green600,
                        Primary.Green700,
                        Primary.Green200,
                        Accent.Red100,
                        TextShade.WHITE);

                    break;

                case 1:
                    materialSkinManager.ColorScheme = new ColorScheme(
     materialSkinManager.Theme == MaterialSkinManager.Themes.DARK ? Primary.Teal500 : Primary.Indigo500,
     materialSkinManager.Theme == MaterialSkinManager.Themes.DARK ? Primary.Teal700 : Primary.Indigo700,
     materialSkinManager.Theme == MaterialSkinManager.Themes.DARK ? Primary.Teal200 : Primary.Indigo100,
     Accent.Pink200,
     TextShade.WHITE);
                    break;

                case 2:
                    materialSkinManager.ColorScheme = new ColorScheme(
                        Primary.BlueGrey800,
                        Primary.BlueGrey900,
                        Primary.BlueGrey500,
                        Accent.LightBlue200,
                        TextShade.WHITE);
                    break;
            }
            Invalidate();
        }



        private void materialSwitch4_CheckedChanged(object sender, EventArgs e)
        {
            DrawerUseColors = materialSwitch4.Checked;
        }

        private void materialButton61_Click(object sender, EventArgs e)
        {
            string basePath;
            string folderName = "CAPTS_data";
           // MessageBox.Show("123");

            basePath = Directory.Exists(@"E:\") ? Path.Combine(@"E:\", folderName) :
                      Directory.Exists(@"D:\") ? Path.Combine(@"D:\", folderName) :
                      Path.Combine(@"C:\", folderName);

            // 如果目录不存在，则创建
            if (!Directory.Exists(basePath))
            {
                try
                {
                    Directory.CreateDirectory(basePath);
                }
                catch (Exception ex)
                {
                    // 回退到其他路径或抛出异常
                }
            }
            if (connect_flag == false)
            {
                if (Device_Flag.Equals("1"))
                {
                    CAPTS_Borker1 = new CAPTS_Borker();
                    t3 = CAPTS_Borker.Handle_Received_Application_Message();
                    t4 = CAPTS_Borker.Publish_Application_Message();
                    CAPTS_Borker.AnalyzerType = false;//确认显示器是外接还是原装
                    materialCheckbox4.Enabled = true;
                    comboBox2.Enabled = true;
                    MessageBox.Show("温室气体测量1");
                }
                else if (Device_Flag.Equals("2"))
                {
                    CAPTS_Borker1 = new CAPTS_Picarro();
                    t3 = CAPTS_Picarro.Handle_Received_Application_Message();
                    CAPTS_Borker.AnalyzerType = false;//确认显示器是外接还是原装
                    materialCheckbox4.Enabled = true;
                    comboBox2.Enabled = true;
                    if (!comboBox1.Items.Contains("NH₃："))
                    { comboBox1.Items.Add("NH₃："); }
                    MessageBox.Show("温室气体测量2");
                }
                else if (Device_Flag.Equals("3"))
                {
                    CAPTS_Borker1 = new CAPTS_Borker();
                    CAPTS_Borker.AnalyzerType = true;//确认显示器是外接还是原装
                    numericUpDown1.Visible = false;
                    numericUpDown2.Visible = false;
                    materialLabel23.Visible = false;
                    materialLabel4.Visible = false;
                    materialLabel28.Visible = false;
                    numericUpDown6.Enabled = false;
                    numericUpDown7.Enabled = false;
                    materialCheckbox4.Enabled = false;
                    comboBox2.Enabled = false;
                    numericUpDown11.Enabled = false;
                    materialButton84.Visible = false;
                    materialLabel25.Text = "干燥间隔";
                    comboBox1.Items.Remove("N₂O：");
                    comboBox1.Items.Remove("CH₄：");
                    MessageBox.Show("群体光合测量");
                }
                CAPTS_Borker1.connectSingleChip();//连接串口

                //lastDataReceivedTime = DateTime.Now; // 初始化为当前时间
                //                                     //启动一个定时器，用于检查串口活动
                //dataReceiveTimer = new System.Windows.Forms.Timer();
                //dataReceiveTimer.Interval = 1000; // 检查间隔为1秒
                //dataReceiveTimer.Tick += CAPTS_Borker1.checkDataReceiveTimeout;  //检测单片机工作是否正常
                //dataReceiveTimer.Start();
                // timer1.Start();
                Power_off_Timer = new System.Windows.Forms.Timer();
                Power_off_Timer.Interval = 1000; // 检查间隔为1秒
                Power_off_Timer.Tick += Automatic_power_off;
                if (materialCheckbox1.Checked == true)
                {
                    Power_off_Timer.Start();
                }
                //CAPTS_Borker.str_mcu = new string[16];
                connect_flag = true;
                materialCard2.Enabled = true;
                materialCard4.Enabled = true;
                materialButton59.Enabled = true;
                materialButton60.Enabled = true;
                materialButton61.Enabled = false;
                materialButton25.Enabled = true;
                materialButton84.Enabled  = true;
                if (Device_Flag.Equals("3"))
                {
                    materialButton84.Enabled = false;
                    materialCard4.Enabled = false;
                }
                MaterialSnackBar SnackBarMessage = new MaterialSnackBar("连接成功\r\n", "确认", true);
                SnackBarMessage.Show(this);
            }
        }
        public void Automatic_power_off(object sender, EventArgs e)
        {
            if (isStartByUser == true)//已开机
            {
                if (dateTimePicker2.Text == DateTime.Now.ToString("HH:mm:ss"))//判断当前时间与自动关机时间是否相等
                {
                    materialButton58_Click(null, EventArgs.Empty);
                }
            }
            else
            {
                if (dateTimePicker1.Text == DateTime.Now.ToString("HH:mm:ss"))//判断当前时间与自动关机时间是否相等
                {
                    materialButton59_Click(null, EventArgs.Empty);
                }
            }
        }

        private void materialButton58_Click(object sender, EventArgs e)
        {
            isStartByUser = false;
            isStoppedByUser = true;//用户主动按下停止
            CAPTS_Borker.Pro_State = "measureLoop Stop !!!";
            // CAPTS_Borker1.disposeStream();//关闭写入数据流
            timer2.Stop();
            //RunMearLoop.Abort();
            timer3.Stop();
            //先将之前的线程释放掉
            data_CO2.Clear();
            data_CH4.Clear();
            data_H2O.Clear();
            data_N2O.Clear();
            data_NH3.Clear();
            full_time.Clear();
            chamberList_4.Clear();
            Fit_Data.Clear();
            materialFloatingActionButton1.Enabled = false;
            materialButton58.Enabled = false;
            materialButton8.Enabled = true;
            //materialButton78.Enabled = true;
            materialCard2.Enabled = true;
            materialCard4.Enabled = true;
            materialButton25.Enabled = true;
            materialButton84.Enabled = true;
            materialLabel3.Text = " ";
            materialLabel35.Text = " ";
            StartProgress();
        }
        private void StartProgress()
        {
            materialProgressBar1.Visible = true; // 显示进度条控件
            materialProgressBar1.Minimum = 0; // 设置进度条最小值
            materialProgressBar1.Maximum = 3 * CAPTS_Borker.caseNumber; // 设置进度条最大值
            materialProgressBar1.Value = 0; // 设置进度条初始值
            progress = 0; // 初始化进度
            timer4.Start(); // 开始计时器
        }
        private void materialButton59_Click(object sender, EventArgs e)
        {
            isStartByUser = true;
            //若用户未设置参数就运行则先进行实例化
            if (materialCheckbox2.Checked)
            {
                Is_Customize = true;
                CAPTS_Borker1.ReadData();
                Console.WriteLine(CAPTS_Borker.caseNumber);
                string tx46 = textBox6.Text.ToString();
                // 检查字符串是否为空、空白或 null
                if (string.IsNullOrWhiteSpace(tx46))
                {
                    MaterialSnackBar SnackBarMessage = new MaterialSnackBar("请输入序列号\r\n", "确认", true);
                    SnackBarMessage.Show(this);
                    return;
                }
                tb46 = new string[CAPTS_Borker.caseNumber];
                tb46 = textBox6.Text.ToString()
                                      .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                                      .Where(s => !string.IsNullOrWhiteSpace(s))
                                      .ToArray();
                bool contains = Array.Exists(tb46, element => element == CAPTS_Borker.MasterToSlave.ToString());
                if (CAPTS_Borker.slave_connect && contains)
                {
                    MessageBox.Show("自定义序号不能包含：" + CAPTS_Borker.MasterToSlave.ToString() + "气路，该气路已连接从机");
                    return;
                }
                previousCaseIndex = tb46[0];
                int num = CAPTS_Borker.caseNumber;
                if (tb46.Length != num)
                {
                    MessageBox.Show("自定义序号设置箱数与输入箱数不等！\r\n设置数量："+ CAPTS_Borker.caseNumber);
                }
                else
                {
                    RunMearLoop = new Thread(() => CAPTS_Borker1.measureLoop(Device_Flag, tx46, num));
                    //RunMearLoop = new Thread(CAPTS_Borker1.measureLoop);
                    RunMearLoop.Start();


                    timer2.Start();//开始读取数据
                                   //当选择使用校准程序，则将需要校准的参数进行校准()
                    if (materialCheckbox5.Checked)
                    {
                        CAPTS_Borker.calibrate_state = true;
                    }

                    CAPTS_Borker.LoopSate = true;//开始暂停句柄，是程序正常运转
                    materialButton59.Enabled = false;
                    materialFloatingActionButton1.Enabled = true;
                    materialButton58.Enabled = true;
                    materialButton8.Enabled = false;
                    //materialButton78.Enabled = false;
                    materialCard2.Enabled = false;
                    materialCard4.Enabled = false;
                    CAPTS_Borker.Pro_State = "measureLoop Run !!!";
                    MaterialSnackBar SnackBarMessage = new MaterialSnackBar("系统已开始运行\r\n", "确认", true);
                    SnackBarMessage.Show(this);
                }
            }
            else
            {
                Is_Customize = false;
                //tb46 = new string[CAPTS_Borker.caseNumber];
                //for (int k = 0; k < CAPTS_Borker.caseNumber; k++)
                //{
                //    tb46[k] = (k + 1).ToString();
                //}
                CAPTS_Borker1.ReadData();

                /*将测量箱1-16号编号写给tb46*/
                tb46 = new string[CAPTS_Borker.Master_Number + CAPTS_Borker.Slave_Number];
                for (int i = 0; i < CAPTS_Borker.Master_Number; i++)
                {
                    tb46[i] = Master_array[i];
                }

                // 将Slave_array的前slaveNumber个元素复制到tb46
                for (int i = 0; i < CAPTS_Borker.Slave_Number; i++)
                {
                    tb46[CAPTS_Borker.Master_Number + i] = Slave_array[i];
                }
                previousCaseIndex = tb46[0];
                Console.WriteLine("自动测量！！！"+tb46.Length);

                RunMearLoop = new Thread(() => CAPTS_Borker1.measureLoop(Device_Flag));
                //RunMearLoop = new Thread(CAPTS_Borker1.measureLoop);
                RunMearLoop.Start();


                timer2.Start();//开始读取数据
                               //当选择使用校准程序，则将需要校准的参数进行校准()
                if (materialCheckbox5.Checked)
                {
                    CAPTS_Borker.calibrate_state = true;
                }

                CAPTS_Borker.LoopSate = true;//开始暂停句柄，是程序正常运转
                materialButton59.Enabled = false;
                materialFloatingActionButton1.Enabled = true;
                materialButton58.Enabled = true;
                materialButton8.Enabled = false;
                //materialButton78.Enabled = false;
                materialCard2.Enabled = false;
                materialCard4.Enabled = false;
                materialButton25.Enabled = false;
                materialButton84.Enabled = false;
                CAPTS_Borker.Pro_State = "measureLoop Run !!!";
                MaterialSnackBar SnackBarMessage = new MaterialSnackBar("系统已开始运行\r\n", "确认", true);
                SnackBarMessage.Show(this);
            }
            omd_4 = new OneMeasurementData(CAPTS_Borker.caseNumber);
            chamberList_4 = omd_4.get_measurement_list();
        }

        private void materialButton60_Click(object sender, EventArgs e)
        {
            if (connect_flag == true)
            {
                //timer1.Stop();
                if (comboBox1.Items.Contains("NH₃："))
                { comboBox1.Items.Remove("NH₃："); }
                //dataReceiveTimer.Stop();
                Power_off_Timer.Stop();
                if (Device_Flag.Equals("1"))
                {
                    try
                    {
                        t3.Dispose();
                        t4.Dispose();
                    }
                    catch { }
                    //CAPTS_Borker1.disposeConnect();
                }
                else if (Device_Flag.Equals("2"))
                {
                    try
                    {
                        t3.Dispose();
                        CAPTS_Picarro.CleanUp();
                    }
                    catch { }
                }
                CAPTS_Borker1.DisconncetSingleChip();
                connect_flag = false;
                materialCard2.Enabled = false;
                materialCard4.Enabled = false;
                materialButton59.Enabled = false;
                materialButton61.Enabled = true;
                materialButton60.Enabled = false;
                materialButton25.Enabled = false;
                materialButton84.Enabled = false;
                MaterialSnackBar SnackBarMessage = new MaterialSnackBar("已断开连接\r\n", "确认", true);
                SnackBarMessage.Show(this);
            }
        }

        private void timer4_Tick(object sender, EventArgs e)
        {
            if (progress <= 3 * CAPTS_Borker.caseNumber)
            {
                materialProgressBar1.Value = progress;

                // 更新进度百分比
                string str = Math.Round((100 * progress / (3.0 * CAPTS_Borker.caseNumber)), 2).ToString("#0.00 ") + "%";

                progress++;
            }
            else
            {
                if (materialFloatingActionButton1.Text == "继续")
                {
                    materialFloatingActionButton1.Text = "暂停";
                    materialFloatingActionButton1.Icon = global::CAPTS.Properties.Resources.MaterialSymbolsPause;
                }
                materialProgressBar1.Visible = false; // 隐藏进度条控件
                materialButton59.Enabled = true;
                MaterialSnackBar SnackBarMessage = new MaterialSnackBar("系统已停止\r\n", "确认", true);
                SnackBarMessage.Show(this);
                timer4.Stop(); // 停止计时器
            }
        }

        private async void tabPage1_Enter(object sender, EventArgs e)
        {
            if (materialCheckbox3.Checked)
            {
                CAPTS_Borker.checkBox1_flag = true;
                CAPTS_Borker.Set_temperature = double.Parse(materialTextBox5.Text);
                CAPTS_Borker.Set_air_pressure = double.Parse(materialTextBox2.Text);
            }
            else
            {
                CAPTS_Borker.checkBox1_flag = false;
            }

            try
            {
                using (StreamReader sr = new StreamReader(CAPTS_Borker.SysParameter))
                {
                    string line;
                    while ((line = await sr.ReadLineAsync()) != null)
                    {
                        if (line.Contains("PT:"))
                        {
                            string[] str1 = line.Split(':');
                            string[] str2 = str1[1].Split(',');
                            materialTextBox27.Text = str2[0];
                            materialTextBox3.Text = str2[1];
                            materialTextBox5.Text = str2[2];
                            materialTextBox2.Text = str2[3];
                            numericUpDown8.Value = int.Parse(str2[4]);
                            numericUpDown9.Value = int.Parse(str2[5]);
                            Setting.CHAMBER_VOLUMN = double.Parse(materialTextBox27.Text);
                            Setting.CHAMBER_GROUND_AREA = double.Parse(materialTextBox3.Text);
                            Setting.PRE_DELETE_TIME = Convert.ToInt32(numericUpDown8.Value);
                            Setting.LOG_DURATION_CUTOFF = Convert.ToInt32(numericUpDown9.Value);
                        }
                        else if (line.StartsWith("TIM:"))
                        {
                            string[] times = line.Substring("TIM:".Length).Trim().Split(',');
                            if (times.Length == 2)
                            {
                                time_start = times[0].Trim();
                                time_stop = times[1].Trim();
                            }
                        }
                        else if (line.StartsWith("SLA:"))
                        {
                            string[] str1 = line.Split(':');
                            string[] str2 = str1[1].Split(',');
                            CAPTS_Borker.MasterToSlave = int.Parse(str2[0]);
                        }
                        else if (line.StartsWith("F:"))
                        {
                            string[] str1 = line.Split(':');
                            string[] str2 = str1[1].Split(',');
                            int Is_Connect1 = int.Parse(str2[0]);
                            materialCheckbox4.Checked = Is_Connect1 == 1;
                            CAPTS_Borker.slave_connect = Is_Connect1 == 1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"文件读取失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }




        void Points_Add(Series series1, List<DateTime> TIME, List<double> DATA)
        {
            if (TIME.Count == 0 || DATA.Count == 0)
            {
                return;
            }

            DateTime startTime = TIME[0];
            int j = 0;

            for (int i = 0; i < full_time.Count; i++)
            {
                DateTime fullTime = full_time[i];
                int seconds1 = (int)(fullTime - startTime).TotalSeconds;

                // 跳过负值
                if (seconds1 < 0)
                {
                    continue;
                }

                if (j < TIME.Count)
                {
                    DateTime time = TIME[j];
                    int seconds = (int)(time - startTime).TotalSeconds;

                    if (seconds1 == seconds)
                    {
                        series1.Points.AddXY(seconds, DATA[j]);
                        j++;
                    }
                    else
                    {
                        series1.Points.AddXY(seconds1, double.NaN);
                    }
                }
                else
                {
                    series1.Points.AddXY(seconds1, double.NaN);
                }
            }
        }
        public void get_realtimedata(Series series1, String selectedOption)
        {
            String currentCaseIndex = CAPTS_Borker.caseIndex.ToString();
            if (Device_Flag.Equals("3"))
            {

                if (currentCaseIndex != previousCaseIndex)
                {
                    chart1.Titles.Clear();//清除图表数据
                    series1.Points.Clear();
                }
                switch (selectedOption)
                {
                    case "CO₂：":
                        // 获取Option 1对应的数据
                        // 执行相应操作
                        chart1.Titles.Clear();//每次点击先清空之前的数据
                        series1.Points.Clear();
                        for (int i = 0; i < data_CO2.Count; i++)
                        {

                            series1.Points.Add(data_CO2[i]);
                        }

                        // Points_Add(series1, chamberList_4[CAPTS_Borker.caseIndex - 1].time_4, chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4);
                        chart1.Titles.Add(selectedOption + "-时间变化图"); // 设置新的选择图表标题
                        chart1.ChartAreas[0].AxisX.Title = "时间/s"; // 设置X轴标题
                        chart1.ChartAreas[0].AxisY.Title = selectedOption + "/ppm"; // 设置Y轴标题                       


                        if (data_CO2.Count > 2)
                        {
                            // 获取纵轴对象
                            var yAxis = chart1.ChartAreas[0].AxisY;
                            /// 设置纵轴范围，若未预热完成，则y轴区间取0~10
                            if (data_CO2.Min() == data_CO2.Max())
                            {
                                yAxis.Minimum = data_CO2.Min() - 10.0;
                                yAxis.Maximum = data_CO2.Min() + 10.0;
                            }
                            else
                            {
                                yAxis.Minimum = data_CO2.Min();
                                yAxis.Maximum = data_CO2.Max();
                            }
                        }


                        series1.LegendText = selectedOption;
                        materialTextBox13.Text = ("斜率:" + Math.Round(CO2_slope, 3).ToString() + " 截距:" + Math.Round(CO2_intercept, 3).ToString());
                        break;

                    case "H₂O：":
                        // 获取Option 2对应的数据
                        // 执行相应操作
                        chart1.Titles.Clear();//每次点击先清空之前的数据
                        series1.Points.Clear();
                        if (data_H2O.Count != 0)
                        {
                            for (int i = 0; i < data_H2O.Count; i++)
                            {

                                series1.Points.Add(data_H2O[i]);
                            }

                            // Points_Add(series1, chamberList_4[CAPTS_Borker.caseIndex - 1].time_4, chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4);
                            chart1.Titles.Add(selectedOption + "-时间变化图"); // 设置新的选择图表标题
                            chart1.ChartAreas[0].AxisX.Title = "时间/s"; // 设置X轴标题
                            chart1.ChartAreas[0].AxisY.Title = selectedOption + "/ppm"; // 设置Y轴标题                       


                            if (data_H2O.Count > 2)
                            {
                                // 获取纵轴对象
                                var yAxis = chart1.ChartAreas[0].AxisY;
                                /// 设置纵轴范围，若未预热完成，则y轴区间取0~10
                                if (data_H2O.Min() == data_H2O.Max())
                                {
                                    yAxis.Minimum = data_H2O.Min() - 10.0;
                                    yAxis.Maximum = data_H2O.Min() + 10.0;
                                }
                                else
                                {
                                    yAxis.Minimum = data_H2O.Min();
                                    yAxis.Maximum = data_H2O.Max();
                                }
                            }
                        }


                        series1.LegendText = selectedOption;
                        materialTextBox13.Text = ("斜率:" + Math.Round(H2O_slope, 3).ToString() + " 截距:" + Math.Round(H2O_intercept, 3).ToString());
                        break;
                }
                }
            else
            {
                if (currentCaseIndex != previousCaseIndex)
                {
                    chart1.Titles.Clear();//清除图表数据
                    series1.Points.Clear();
                }
                switch (selectedOption)
                {
                    case "CO₂：":
                        // 获取Option 1对应的数据
                        // 执行相应操作
                        chart1.Titles.Clear();//每次点击先清空之前的数据
                        series1.Points.Clear();
                        if (chamberList_4.Count != 0)
                        {
                            Points_Add(series1, chamberList_4[CAPTS_Borker.caseIndex - 1].time_4, chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4);
                            chart1.Titles.Add(selectedOption + "-时间变化图"); // 设置新的选择图表标题
                            chart1.ChartAreas[0].AxisX.Title = "时间/s"; // 设置X轴标题
                            chart1.ChartAreas[0].AxisY.Title = selectedOption + "/ppm"; // 设置Y轴标题                       


                            if (chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4.Count > 2)
                            {
                                // 获取纵轴对象
                                var yAxis = chart1.ChartAreas[0].AxisY;
                                // 设置纵轴范围，若未预热完成，则y轴区间取0~10
                                if (chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4.Min() == chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4.Max())
                                {
                                    yAxis.Minimum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4.Min() - 10.0;
                                    yAxis.Maximum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4.Min() + 10.0;
                                }
                                else
                                {
                                    yAxis.Minimum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4.Min();
                                    yAxis.Maximum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4.Max();
                                }
                            }
                        }

                        series1.LegendText = selectedOption;
                        materialTextBox13.Text = ("斜率:" + Math.Round(CO2_slope, 3).ToString() + " 截距:" + Math.Round(CO2_intercept, 3).ToString());
                        break;

                    case "H₂O：":
                        // 获取Option 2对应的数据
                        // 执行相应操作
                        chart1.Titles.Clear();//每次点击先清空之前的数据
                        series1.Points.Clear();
                        if (chamberList_4.Count != 0)
                        {
                            Points_Add(series1, chamberList_4[CAPTS_Borker.caseIndex - 1].time_4, chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4);
                            chart1.Titles.Add(selectedOption + "-时间变化图"); // 设置新的选择图表标题
                            chart1.ChartAreas[0].AxisX.Title = "时间/s"; // 设置X轴标题
                            chart1.ChartAreas[0].AxisY.Title = selectedOption + "/ppm"; // 设置Y轴标题                       


                            if (chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4.Count > 2)
                            {
                                // 获取纵轴对象
                                var yAxis = chart1.ChartAreas[0].AxisY;
                                // 设置纵轴范围，若未预热完成，则y轴区间取0~10
                                if (chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4.Min() == chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4.Max())
                                {
                                    yAxis.Minimum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4.Min() - 10.0;
                                    yAxis.Maximum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4.Min() + 10.0;
                                }
                                else
                                {
                                    yAxis.Minimum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4.Min();
                                    yAxis.Maximum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4.Max();
                                }
                            }
                        }


                        series1.LegendText = selectedOption;
                        materialTextBox13.Text = ("斜率:" + Math.Round(H2O_slope, 3).ToString() + " 截距:" + Math.Round(H2O_intercept, 3).ToString());
                        break;

                    case "CH₄："://数据用来测试
                                // 获取Option 3对应的数据
                                // 执行相应操作
                        chart1.Titles.Clear();//每次点击先清空之前的数据
                        series1.Points.Clear();
                        if (chamberList_4.Count != 0)
                        {
                            Points_Add(series1, chamberList_4[CAPTS_Borker.caseIndex - 1].time_4, chamberList_4[CAPTS_Borker.caseIndex - 1].data_CH4_4);
                            chart1.Titles.Add(selectedOption + "-时间变化图"); // 设置新的选择图表标题
                            chart1.ChartAreas[0].AxisX.Title = "时间/s"; // 设置X轴标题
                            chart1.ChartAreas[0].AxisY.Title = selectedOption + "/ppm"; // 设置Y轴标题                       


                            if (chamberList_4[CAPTS_Borker.caseIndex - 1].data_CH4_4.Count > 2)
                            {
                                // 获取纵轴对象
                                var yAxis = chart1.ChartAreas[0].AxisY;
                                // 设置纵轴范围，若未预热完成，则y轴区间取0~10
                                if (chamberList_4[CAPTS_Borker.caseIndex - 1].data_CH4_4.Min() == chamberList_4[CAPTS_Borker.caseIndex - 1].data_CH4_4.Max())
                                {
                                    yAxis.Minimum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_CH4_4.Min() - 10.0;
                                    yAxis.Maximum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_CH4_4.Min() + 10.0;
                                }
                                else
                                {
                                    yAxis.Minimum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_CH4_4.Min();
                                    yAxis.Maximum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_CH4_4.Max();
                                }
                            }
                        }

                        series1.LegendText = selectedOption;
                        materialTextBox13.Text = ("斜率:" + Math.Round(CH4_slope, 3).ToString() + " 截距:" + Math.Round(CH4_intercept, 3).ToString());
                        break;

                    case "N₂O：":
                        // 获取Option 3对应的数据
                        // 执行相应操作
                        chart1.Titles.Clear();//每次点击先清空之前的数据
                        series1.Points.Clear();
                        if (chamberList_4.Count != 0)
                        {
                            Points_Add(series1, chamberList_4[CAPTS_Borker.caseIndex - 1].time_4, chamberList_4[CAPTS_Borker.caseIndex - 1].data_N2O_4);
                            chart1.Titles.Add(selectedOption + "-时间变化图"); // 设置新的选择图表标题
                            chart1.ChartAreas[0].AxisX.Title = "时间/s"; // 设置X轴标题
                            chart1.ChartAreas[0].AxisY.Title = selectedOption + "/ppm"; // 设置Y轴标题                       


                            if (chamberList_4[CAPTS_Borker.caseIndex - 1].data_N2O_4.Count > 2)
                            {
                                // 获取纵轴对象
                                var yAxis = chart1.ChartAreas[0].AxisY;
                                // 设置纵轴范围，若未预热完成，则y轴区间取0~10
                                if (chamberList_4[CAPTS_Borker.caseIndex - 1].data_N2O_4.Min() == chamberList_4[CAPTS_Borker.caseIndex - 1].data_N2O_4.Max())
                                {
                                    yAxis.Minimum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_N2O_4.Min() - 10.0;
                                    yAxis.Maximum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_N2O_4.Min() + 10.0;
                                }
                                else
                                {
                                    yAxis.Minimum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_N2O_4.Min();
                                    yAxis.Maximum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_N2O_4.Max();
                                }
                            }
                        }

                        series1.LegendText = selectedOption;
                        materialTextBox13.Text = ("斜率:" + Math.Round(N2O_slope, 3).ToString() + " 截距:" + Math.Round(N2O_intercept, 3).ToString());
                        break;
                    case "NH₃：":
                        // 获取Option 3对应的数据
                        // 执行相应操作
                        chart1.Titles.Clear();//每次点击先清空之前的数据
                        series1.Points.Clear();
                        if (chamberList_4.Count != 0)
                        {
                            Points_Add(series1, chamberList_4[CAPTS_Borker.caseIndex - 1].time_4, chamberList_4[CAPTS_Borker.caseIndex - 1].data_NH3_4);
                            chart1.Titles.Add(selectedOption + "-时间变化图"); // 设置新的选择图表标题
                            chart1.ChartAreas[0].AxisX.Title = "时间/s"; // 设置X轴标题
                            chart1.ChartAreas[0].AxisY.Title = selectedOption + "/ppm"; // 设置Y轴标题                       


                            if (chamberList_4[CAPTS_Borker.caseIndex - 1].data_NH3_4.Count > 2)
                            {
                                // 获取纵轴对象
                                var yAxis = chart1.ChartAreas[0].AxisY;
                                // 设置纵轴范围，若未预热完成，则y轴区间取0~10
                                if (chamberList_4[CAPTS_Borker.caseIndex - 1].data_NH3_4.Min() == chamberList_4[CAPTS_Borker.caseIndex - 1].data_NH3_4.Max())
                                {
                                    yAxis.Minimum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_NH3_4.Min() - 10.0;
                                    yAxis.Maximum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_NH3_4.Min() + 10.0;
                                }
                                else
                                {
                                    yAxis.Minimum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_NH3_4.Min();
                                    yAxis.Maximum = chamberList_4[CAPTS_Borker.caseIndex - 1].data_NH3_4.Max();
                                }
                            }
                        }
                        series1.LegendText = selectedOption;
                        materialTextBox13.Text = ("斜率:" + Math.Round(NH3_slope, 3).ToString() + " 截距:" + Math.Round(NH3_intercept, 3).ToString());
                        break;
                    // 添加更多选项及其对应的操作
                    default:
                        // 默认操作（如果选择了未处理的选项）
                        break;
                }
            }

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem != null)
            {
                string selectedOption = comboBox1.SelectedItem.ToString();
                Series series1 = chart1.Series["线性图1"];
                //执行实时显示数据操作
                if (isStartByUser == true)
                {
                    timer3.Start();
                }
                get_realtimedata(series1, selectedOption);
                // 其他操作... 
            }
            else
            {

            }
        }

        private void materialComboBox8_SelectedIndexChanged(object sender, EventArgs e)
        {
            combox_selectedIndex = materialComboBox8.SelectedIndex;
        }

        private void timer2_Tick(object sender, EventArgs e)//将数据每1 秒刷新一次填进视图里
        {
            label19.Text = state;
            /*测试，将串口接收数据显示到界面方便调试*/
            if (Debug_Button)
            { textBox8.Text = serial_test_dis; }
            if (state == "Measuring")
            {
                
                CAPTS_Suite.DataLine dl = new CAPTS_Suite.DataLine();
                dl.time_string = DateTime.Now.ToString("HH:mm:ss");
                int seconds = convertTime2sec(DateTime.Now.ToString("HH:mm:ss"));
                dl.seconds = seconds;
                //Console.WriteLine(seconds.ToString());
                //Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
                this.Invoke((EventHandler)(delegate
                {
                    if (CAPTS_Borker.AnalyzerType)//判断是外接分析器还是原机分析器
                    {   //原机分析
                        data_CO2.Add(Double.Parse(ChipPackages.C_CO2));
                        data_H2O.Add(Double.Parse(ChipPackages.C_H2O));
                        dl.co2 = Double.Parse(ChipPackages.C_CO2);
                        dl.h2o = Double.Parse(ChipPackages.C_H2O);

                        //timer1 移动到timer2了
                        data_chart[0][1] = ChipPackages.C_CO2;
                        data_chart[1][1] = ChipPackages.C_H2O;
                        data_chart[2][1] = "0";
                        data_chart[3][1] = "0";

                    }


                    else
                    {
                        try
                        {
                            if (Device_Flag.Equals("1"))
                            {
                                data_CO2.Add(Double.Parse(CAPTS_Borker.LI_CO2));
                                data_H2O.Add(Double.Parse(CAPTS_Borker.LI_H2O));
                                data_CH4.Add(Double.Parse(CAPTS_Borker.LI_CH4));
                                data_N2O.Add(Double.Parse(CAPTS_Borker.LI_N2O));
                                dl.co2 = Double.Parse(CAPTS_Borker.LI_CO2);
                                dl.h2o = Double.Parse(CAPTS_Borker.LI_H2O);
                                dl.ch4 = Double.Parse(CAPTS_Borker.LI_CH4);
                                dl.n2o = Double.Parse(CAPTS_Borker.LI_N2O);


                                data_chart[0][1] = CAPTS_Borker.LI_CO2;//二氧化碳显示在桌面上
                                data_chart[1][1] = CAPTS_Borker.LI_H2O;
                                data_chart[2][1] = CAPTS_Borker.LI_CH4;
                                data_chart[3][1] = CAPTS_Borker.LI_N2O;
                                //Random ran = new Random();
                                //int n = ran.Next(100);
                                //data_CO2.Add(n);
                                //dl.co2 = n;
                            }
                            else if (Device_Flag.Equals("2"))
                            {
                                data_CO2.Add(Double.Parse(CAPTS_Picarro.PI_CO2_dry));
                                data_H2O.Add(Double.Parse(CAPTS_Picarro.PI_H2O));
                                data_CH4.Add(Double.Parse(CAPTS_Picarro.PI_CH4_dry));
                                data_N2O.Add(Double.Parse(CAPTS_Picarro.PI_N2O_dry));
                                data_NH3.Add(Double.Parse(CAPTS_Picarro.PI_NH3));
                                dl.co2 = Double.Parse(CAPTS_Picarro.PI_CO2_dry);
                                dl.h2o = Double.Parse(CAPTS_Picarro.PI_H2O);
                                dl.ch4 = Double.Parse(CAPTS_Picarro.PI_CH4_dry);
                                dl.n2o = Double.Parse(CAPTS_Picarro.PI_N2O_dry);
                                dl.nh3 = Double.Parse(CAPTS_Picarro.PI_NH3);
                                //timer1 移动到timer2
                                data_chart[0][1] = CAPTS_Picarro.PI_CO2;//二氧化碳显示在桌面上
                                data_chart[1][1] = CAPTS_Picarro.PI_H2O;
                                data_chart[2][1] = CAPTS_Picarro.PI_CH4;
                                data_chart[3][1] = CAPTS_Picarro.PI_N2O;
                                data_chart[4][1] = CAPTS_Picarro.PI_NH3;
                            }
                            else
                            {
                                data_CO2.Add(Double.Parse(ChipPackages.C_CO2));
                                data_H2O.Add(Double.Parse(ChipPackages.C_H2O));
                               
                                dl.co2 = Double.Parse(ChipPackages.C_CO2);
                                dl.h2o = Double.Parse(ChipPackages.C_H2O);

                                //timer1 移动到timer2了
                                data_chart[0][1] = ChipPackages.C_CO2;
                                data_chart[1][1] = ChipPackages.C_H2O;
                                data_chart[2][1] = "0";
                                data_chart[3][1] = "0";
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                    }
                    //timer1 移动到timer2
                    materialLabel36.Text = ChipPackages.C_FLOW.ToString();
                    data_chart[5][1] = ChipPackages.C_T;
                    data_chart[6][1] = ChipPackages.C_HR;
                    data_chart[7][1] = ChipPackages.C_PPFD;
                    data_chart[8][1] = ChipPackages.C_PA;
                    materialListView2.Items.Clear();
                    foreach (string[] version in data_chart)
                    {
                        var item = new ListViewItem(version);
                        materialListView2.Items.Add(item);
                    }
                    if (isStartByUser == true)
                    {
                        if (CAPTS_Borker.casein >= 0 && CAPTS_Borker.casein < tb46.Length)
                        {
                            materialLabel3.Text = tb46[CAPTS_Borker.casein].ToString();
                        }
                        materialLabel35.Text = CAPTS_Borker.currentLoop.ToString();

                    }
                    //String currentCaseIndex = CAPTS_Borker.caseIndex.ToString();
                    //String previousCaseIndex = CAPTS_Borker.caseIndex.ToString();
                    //if (currentCaseIndex == previousCaseIndex)
                    //{ 
                    //}

                    if (Convert.ToInt32(ChipPackages.C_FLOW) < 1000)
                    {
                        //textBox8.Text = "Error: flow rate is too low!"; //measureLoop Run !!!
                    }

                    //判断是否使用默认温度压强
                    if (materialCheckbox3.Checked)
                    {
                        //用户自定义温度、压强
                        dl.temperature = Double.Parse(materialTextBox5.Text);
                        dl.air_pressure = Double.Parse(materialTextBox2.Text);
                    }
                    else
                    {
                        dl.temperature = Double.Parse(ChipPackages.C_T);
                        dl.air_pressure = Double.Parse(ChipPackages.C_PA);
                    }
                    dl.ppfd = Double.Parse(ChipPackages.C_PPFD);
                    dl.relative_humidity = Double.Parse(ChipPackages.C_HR);
                }
                )
                );
                om.add_rawData(dl);

                //判断测量箱是否改变，若发生改变则进行上次测量AC，EC等数据的计算
                String currentCaseIndex = CAPTS_Borker.caseIndex.ToString();
                if (currentCaseIndex != previousCaseIndex)
                {
                    // 设备编号发生了改变
                    // 在这里编写处理设备编号改变的逻辑
                    // 比如触发事件、更新界面等
                    // 生成相同大小的时间序列作为 x 轴数据,作CO2拟合
                    Fit fit_CO2 = new Fit();
                    List<double> xCO2 = new List<double>();
                    for (int i = 0; i < data_CO2.Count; i++)
                    {
                        xCO2.Add(i * 1.0); // 每隔一秒表示一个单位的时间
                    }
                    fit_CO2.linearFit(xCO2, data_CO2);
                    CO2_slope = Math.Round(fit_CO2.getSlope(), 2);
                    CO2_intercept = Math.Round(fit_CO2.getIntercept(), 2);

                    // 生成相同大小的时间序列作为 x 轴数据,作CH4拟合
                    Fit fit_CH4 = new Fit();
                    List<double> xCH4 = new List<double>();
                    for (int i = 0; i < data_CH4.Count; i++)//改成CH4
                    {
                        xCH4.Add(i * 1.0); // 每隔一秒表示一个单位的时间
                    }
                    fit_CH4.linearFit(xCH4, data_CH4);
                    CH4_slope = Math.Round(fit_CH4.getSlope(), 2);
                    CH4_intercept = Math.Round(fit_CH4.getIntercept(), 2);
                    //Console.WriteLine("CH4_slope:" + CH4_slope);
                    // 生成相同大小的时间序列作为 x 轴数据,作H2O拟合
                    Fit fit_H2O = new Fit();
                    List<double> xH2O = new List<double>();
                    for (int i = 0; i < data_H2O.Count; i++)
                    {
                        xH2O.Add(i * 1.0); // 每隔一秒表示一个单位的时间
                    }
                    fit_H2O.linearFit(xH2O, data_H2O);
                    H2O_slope = Math.Round(fit_H2O.getSlope(), 2);
                    H2O_intercept = Math.Round(fit_H2O.getIntercept(), 2);
                    // 生成相同大小的时间序列作为 x 轴数据,作N2O拟合
                    Fit fit_N2O = new Fit();
                    List<double> xN2O = new List<double>();
                    for (int i = 0; i < data_N2O.Count; i++)
                    {
                        xN2O.Add(i * 1.0); // 每隔一秒表示一个单位的时间
                    }
                    fit_N2O.linearFit(xN2O, data_N2O);
                    N2O_slope = Math.Round(fit_N2O.getSlope(), 2);
                    N2O_intercept = Math.Round(fit_N2O.getIntercept(), 2);
                    // 生成相同大小的时间序列作为 x 轴数据,作NH3拟合
                    Fit fit_NH3 = new Fit();
                    List<double> xNH3 = new List<double>();
                    for (int i = 0; i < data_NH3.Count; i++)
                    {
                        xNH3.Add(i * 1.0); // 每隔一秒表示一个单位的时间
                    }
                    fit_NH3.linearFit(xNH3, data_NH3);
                    NH3_slope = Math.Round(fit_NH3.getSlope(), 2);
                    NH3_intercept = Math.Round(fit_NH3.getIntercept(), 2);
                    //获取本次测量中1Ac，Ec等、气体浓度平均值等数据
                    om.update();
                    Console.WriteLine("csv:" + om.Ac_Li + "  " + om.Ec_Li + "  " + om.MER_Li + "  " + om.N2OER_Li + "  " + om.NH3ER_PI + "  " + om.AcR2);
                    double AC = Math.Round(om.Ac_Li, 2);


                    double EC = Math.Round(om.Ec_Li, 2);
                    double MER = Math.Round(om.MER_Li, 2);
                    double N2OER = Math.Round(om.N2OER_Li, 2);
                    double NH3ER = Math.Round(om.NH3ER_PI, 2);
                    double R2 = Math.Round(om.AcR2, 2);
                    double ppfd_cov = Math.Round(om.CvPPFD, 2);
                    //获取本次测量中的平均数据
                    CAPTS_Suite.DataLine avgdata = om.get_avgData();
                    double temperature = avgdata.temperature;
                    double relative_humidity = avgdata.relative_humidity;
                    double ppfd = avgdata.ppfd;
                    double air_pressure = avgdata.air_pressure;
                    double CO2 = avgdata.co2;
                    double h2o = avgdata.h2o;
                    double ch4 = avgdata.ch4;
                    double n2o = avgdata.n2o;
                    double nh3 = avgdata.nh3;
                    materialMultiLineTextBox22.Text = "AC:" + AC + "  EC:" + EC + Environment.NewLine + "MER:" + MER + "  N2O:" + N2OER + "  NH3:" + NH3ER;
                    //保存数据AC-EC
                    //string str = "AC-EC:";
                    //string ctime = DateTime.Now.ToString("yyyyMMdd");//换成了_startTime
                    int year = DateTime.Now.Year;
                    int month = DateTime.Now.Month;
                    int day = DateTime.Now.Day;
                    int doy = DateTime.Now.DayOfYear;
                    string currentTime = DateTime.Now.ToString("HH:mm:ss");
                    int sod = (int)DateTime.Now.TimeOfDay.TotalSeconds;
                    //若E盘存在则存储至E盘CAPTS_data文件下，否则存储至D盘CAPTS_data文件下
                    //string Epath_1 = @"E:\CAPTS_data\";
                    //string ACECfile = "";
                    //if (Directory.Exists(Epath_1))
                    //{
                    //    ACECfile = @"E:\\CAPTS_data\" + CAPTS_Borker._startTime.ToString("yyyyMMdd") + "ACEC.csv";
                    //}
                    //else
                    //{
                    //    ACECfile = @"D:\\CAPTS_data\" + CAPTS_Borker._startTime.ToString("yyyyMMdd") + "ACEC.csv";
                    //}
                    //string str = null;
                    //if (Device_Flag.Equals("1"))
                    //{
                    //    str = previousCaseIndex + ";" + year.ToString() + ";" + month.ToString() + ";" + day.ToString() + ";" + doy.ToString() + ";" + currentTime.ToString() + ";" +
                    //   seconds.ToString() + ";" + temperature.ToString() + ";" + relative_humidity.ToString() + ";" + ppfd.ToString() + ";" + air_pressure.ToString() + ";" +
                    //   CO2.ToString() + ";" + h2o.ToString() + ";" + ch4.ToString() + ";" + n2o.ToString() + ";" + AC.ToString() + ";" + EC.ToString() + ";" +
                    //   MER.ToString() + ";" + N2OER.ToString() + ";" + R2.ToString() + ";" + ppfd_cov.ToString();
                    //}
                    //else if (Device_Flag.Equals("2"))
                    //{
                    //    str = previousCaseIndex + ";" + year.ToString() + ";" + month.ToString() + ";" + day.ToString() + ";" + doy.ToString() + ";" + currentTime.ToString() + ";" +
                    //   seconds.ToString() + ";" + temperature.ToString() + ";" + relative_humidity.ToString() + ";" + ppfd.ToString() + ";" + air_pressure.ToString() + ";" +
                    //   CO2.ToString() + ";" + h2o.ToString() + ";" + ch4.ToString() + ";" + n2o.ToString() + ";" + AC.ToString() + ";" + EC.ToString() + ";" +
                    //   MER.ToString() + ";" + N2OER.ToString() + ";" + NH3ER.ToString() + ";" + R2.ToString() + ";" + ppfd_cov.ToString();
                    //}
                    //string[] str1 = str.Split(';');
                    //// 创建 StreamWriter 对象，将数据写入文件
                    //if (!File.Exists(ACECfile))
                    //{
                    //    if (Device_Flag.Equals("1"))
                    //    {
                    //        // 表头数
                    //        string[] headers = {"chamberID","year","month","day", "DOY", "time", "seconds", "temperature(oC)", "relative humidity(%)"
                    //    ,"PPFD(umol.m-2.s-1)","air pressure(kPa)","CO2(ppm)","H2O(ppt)", "CH4(ppb)", "N2O(ppb)",
                    //     "Ac(umol.m-2 ground area.s-1)", "Ec(mmol.m-2 ground area.s-1)","MER(umol.m-2 ground area.s-1)","N2OER(umol.m-2 ground area.s-1)",
                    //        "R2 (CO2 linear fitting)", "PPFD coefficient of variation (%)"};
                    //        using (StreamWriter writer = File.CreateText(ACECfile))
                    //        {
                    //            writer.WriteLine(string.Join(",", headers));
                    //            writer.WriteLine(string.Join(",", str1));
                    //        }
                    //        Console.WriteLine("AC-EC数据等已成功写入新文件！");
                    //    }
                    //    else if (Device_Flag.Equals("2"))
                    //    {
                    //        // 表头数
                    //        string[] headers = {"chamberID","year","month","day", "DOY", "time", "seconds", "temperature(oC)", "relative humidity(%)"
                    //    ,"PPFD(umol.m-2.s-1)","air pressure(kPa)","CO2(ppm)","H2O(ppt)", "CH4(ppb)", "N2O(ppb)",
                    //     "Ac(umol.m-2 ground area.s-1)","CO2_Mean","CO2_StdDev", "Ec(mmol.m-2 ground area.s-1)","H2O_Mean","H2O_StdDev","MER(umol.m-2 ground area.s-1)","CH4_Mean","CH4_StdDev","N2OER(umol.m-2 ground area.s-1)","N2O_Mean","N2O_StdDev",
                    //        "NH3ER(umol.m-2 ground area.s-1)","NH3_Mean","NH3_StdDev","R2 (CO2 linear fitting)", "PPFD coefficient of variation (%)"};
                    //        using (StreamWriter writer = File.CreateText(ACECfile))
                    //        {
                    //            writer.WriteLine(string.Join(",", headers));
                    //            writer.WriteLine(string.Join(",", str1));
                    //        }
                    //        Console.WriteLine("AC-EC数据等已成功写入新文件！");
                    //    }
                    //}
                    //else
                    //{
                    //    using (StreamWriter writer = new StreamWriter(ACECfile, true))
                    //    {
                    //        writer.WriteLine(string.Join(",", str1));
                    //    }
                    //    Console.WriteLine("AC-EC数据已成功写入文件！");
                    //}
                    ////保存四种气体的斜率
                    ////若E盘存在则存储至E盘CAPTS_data文件下，否则存储至D盘CAPTS_data文件下
                    //string Epath_2 = @"E:\CAPTS_data\";
                    //string slopefile = "";
                    //if (Directory.Exists(Epath_2))
                    //{
                    //    slopefile = @"E:\\CAPTS_data\" + CAPTS_Borker._startTime.ToString("yyyyMMdd") + "slope.txt";
                    //}
                    //else
                    //{
                    //    slopefile = @"D:\\CAPTS_data\" + CAPTS_Borker._startTime.ToString("yyyyMMdd") + "slope.txt";
                    //}
                    //string str2 = DateTime.Now.ToString() + "," + "ChamberID：" + previousCaseIndex + "," + CO2_slope.ToString() + "," + H2O_slope.ToString() + "," + CH4_slope.ToString() + "," + N2O_slope.ToString() + "," + NH3_slope.ToString();
                    //if (!File.Exists(slopefile))
                    //{
                    //    using (StreamWriter writer = File.CreateText(slopefile))
                    //    {
                    //        writer.WriteLine("Order of Data：Time；CO2; H2O; CH4; N2O；NH3");
                    //        writer.WriteLine(str2);
                    //    }
                    //    Console.WriteLine("slopedata数据已成功写入新文件！");
                    //}
                    //else
                    //{
                    //    using (StreamWriter writer = new StreamWriter(slopefile, true))
                    //    {
                    //        writer.WriteLine(str2);
                    //    }
                    //    Console.WriteLine("slopedata数据已成功写入文件！");
                    //}
                    //切换测量箱设备时清除并重新获取新数据
                    previousCaseIndex = currentCaseIndex;
                    data_CO2.Clear();
                    data_CH4.Clear();
                    data_H2O.Clear();
                    data_N2O.Clear();
                    data_NH3.Clear();
                    om = new OneChamber();
                }
                else
                {

                }
            }
            else
            {
                materialLabel3.Text = state;
                materialLabel35.Text = state;
            }
        }

        private void MaterialSwitch5_CheckedChanged(object sender, EventArgs e)
        {
            DrawerHighlightWithAccent = materialSwitch5.Checked;
        }

        private void MaterialSwitch6_CheckedChanged(object sender, EventArgs e)
        {
            DrawerBackgroundWithAccent = materialSwitch6.Checked;
        }


        private void timer1_Tick(object sender, EventArgs e)//将数据每秒刷新一次显示在桌面上
        {
            this.Invoke((EventHandler)(delegate
            {
                if (CAPTS_Borker.AnalyzerType)//判断是外接分析器还是原机分析器
                {   //原机分析
                    data_chart[0][1] = ChipPackages.C_CO2;
                    data_chart[1][1] = ChipPackages.C_H2O;
                    data_chart[2][1] = "0";
                    data_chart[3][1] = "0";
                }
                else
                {
                    if (Device_Flag.Equals("1"))
                    {
                        data_chart[0][1] = CAPTS_Borker.LI_CO2;//二氧化碳显示在桌面上
                        data_chart[1][1]= CAPTS_Borker.LI_H2O;
                        data_chart[2][1] = CAPTS_Borker.LI_CH4;
                        data_chart[3][1] = CAPTS_Borker.LI_N2O;
                    }
                    else if (Device_Flag.Equals("2"))
                    {
                        data_chart[0][1] = CAPTS_Picarro.PI_CO2;//二氧化碳显示在桌面上
                        data_chart[1][1]= CAPTS_Picarro.PI_H2O;
                        data_chart[2][1] = CAPTS_Picarro.PI_CH4;
                        data_chart[3][1] = CAPTS_Picarro.PI_N2O;
                        data_chart[4][1] = CAPTS_Picarro.PI_NH3;
                    }


                }
                data_chart[5][1] = ChipPackages.C_T;
                data_chart[6][1] = ChipPackages.C_HR;
                data_chart[7][1] = ChipPackages.C_PPFD;
                data_chart[8][1] = ChipPackages.C_PA;
                materialListView2.Items.Clear();
                foreach (string[] version in data_chart)
                {
                    var item = new ListViewItem(version);
                    materialListView2.Items.Add(item);
                }
                if (isStartByUser == true)
                {
                    if (CAPTS_Borker.casein >= 0 && CAPTS_Borker.casein < tb46.Length)
                    { materialLabel3.Text = tb46[CAPTS_Borker.casein].ToString();
                        if (state != "Measuring")
                        {
                            materialLabel3.Text = state;
                        }
                    }
                }
                                                       //String currentCaseIndex = CAPTS_Borker.caseIndex.ToString();
                                                       //String previousCaseIndex = CAPTS_Borker.caseIndex.ToString();
                                                       //if (currentCaseIndex == previousCaseIndex)
                                                       //{ 
                                                       //}
                if (Convert.ToInt32(ChipPackages.C_FLOW) < 1000)
                {
                    //textBox8.Text = "Error: flow rate is too low!"; //measureLoop Run !!!
                }
            }
            )
           );
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            CAPTS_Borker1 = new CAPTS_Borker();//默认
            Master_array = new string[16];
            Slave_array = new string[16];
            for (int k = 0; k < 16; k++)
            {
                Master_array[k] = (k + 1).ToString();  // k从0开始，k + 1为1到16
            }
            for (int j = 0; j < 16; j++)
            {
                Slave_array[j] = (j + 17).ToString();  // j从0开始，j + 17为17到32
            }
            materialRadioButton6.Checked=true;
            Device_Flag = "3";//LI
           // materialTabControl1.TabPages.Remove(tabPage11);
        }


        private void timer3_Tick(object sender, EventArgs e)
        {
            if (state == "Measuring")
            {
                DateTime now = DateTime.Now;
                try
                {
                    chamberList_4[CAPTS_Borker.caseIndex - 1].time_4.Add(now);
                    full_time.Add(now);
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    // 处理索引超出范围的异常
                    Console.WriteLine($"索引超出范围: {ex.Message}");
                }

                if (Device_Flag.Equals("1"))
                {
                    chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4.Add(Double.Parse(CAPTS_Borker.LI_CO2));
                    chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4.Add(Double.Parse(CAPTS_Borker.LI_H2O));
                    chamberList_4[CAPTS_Borker.caseIndex - 1].data_CH4_4.Add(Double.Parse(CAPTS_Borker.LI_CH4));
                    chamberList_4[CAPTS_Borker.caseIndex - 1].data_N2O_4.Add(Double.Parse(CAPTS_Borker.LI_N2O));
                }
                else if (Device_Flag.Equals("2"))
                {
                    chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4.Add(Double.Parse(CAPTS_Picarro.PI_CO2_dry));
                    chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4.Add(Double.Parse(CAPTS_Picarro.PI_H2O));
                    chamberList_4[CAPTS_Borker.caseIndex - 1].data_CH4_4.Add(Double.Parse(CAPTS_Picarro.PI_CH4_dry));
                    chamberList_4[CAPTS_Borker.caseIndex - 1].data_N2O_4.Add(Double.Parse(CAPTS_Picarro.PI_N2O_dry));
                    chamberList_4[CAPTS_Borker.caseIndex - 1].data_NH3_4.Add(Double.Parse(CAPTS_Picarro.PI_NH3));
                }
                else
                {

                    chamberList_4[CAPTS_Borker.caseIndex - 1].data_CO2_4.Add(Double.Parse(ChipPackages.C_CO2));
                    chamberList_4[CAPTS_Borker.caseIndex - 1].data_H2O_4.Add(Double.Parse(ChipPackages.C_H2O));
                }
                if (CAPTS_Borker.Measure_flag)
                {
                    if (chamberList_4 != null)
                    {
                        // 清除所有 chamberList_4 数据
                        for (int i = 0; i < chamberList_4.Count; i++)
                        {
                            chamberList_4[i].data_CO2_4.Clear();
                            chamberList_4[i].data_H2O_4.Clear();
                            chamberList_4[i].data_CH4_4.Clear();
                            chamberList_4[i].data_N2O_4.Clear();
                            chamberList_4[i].data_NH3_4?.Clear();
                            chamberList_4[i].time_4.Clear();
                        }
                    }
                    else
                    {
                        chamberList_4 = new List<OneChamber>();  // 如果为空，初始化列表
                    }
                    full_time.Clear();

                    materialComboBox8.Items.Add(slope_time.ToString("HH:mm:ss"));
                    if (materialComboBox8.Items.Count >= 11)
                    {
                        materialComboBox8.Items.Clear();
                        Fit_Data.Clear();
                    }
                    CAPTS_Borker.Measure_flag = false;
                }

                comboBox1_SelectedIndexChanged(sender, e);
            }
        }

        private void materialButton8_Click(object sender, EventArgs e)
        {
            //设置时间，箱子数量等参数

            int Cycle_Case_Time = (Convert.ToInt32(numericUpDown1.Value)) * 60 + Convert.ToInt32(numericUpDown2.Value);//numericUpDown1和numericUpDown2是一轮箱子抽气间隔时间
                                                                                                                       // CAPTS_Borker1.setChamberLid("K_Mtime", Meatimes);//将参数传给单片机
            int Signle_Case_Time = Convert.ToInt32(numericUpDown3.Value);//numericUpDown3 是单个箱子抽气时间
            int Loop_Time = Convert.ToInt32(numericUpDown6.Value) * 60 + Convert.ToInt32(numericUpDown7.Value);//numericUpDown6和numericUpDown7为循环间隔时间
                                                                                                               //CAPTS_Borker1.setChamberLid("K_Wtime", Wtimes);
            int Mnumbers = Convert.ToInt32(numericUpDown4.Value);//箱子数目
            int Master_Numbers = Convert.ToInt32(numericUpDown10.Value);//主机测量箱
            int Slave_Numbers = Convert.ToInt32(numericUpDown11.Value);//从机测量箱数目
            int Loop_Count = Convert.ToInt32(numericUpDown5.Value);//循环次数

            if (Loop_Time < Loop_Count * Cycle_Case_Time + 420 && Device_Flag != "3")
            {
                MessageBox.Show("Error：循环总时间需大于循环次数*单次时间+6min(干燥气路时间)");
            }
            else 
            {
                string str = "K:";
                string str1 = Mnumbers.ToString()+","+ Signle_Case_Time.ToString() + "," + Cycle_Case_Time.ToString() + "," + Loop_Time.ToString() + "," + Loop_Count.ToString() + "," + Master_Numbers.ToString() + "," + Slave_Numbers.ToString();
                CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str, str1);//将设置文件保存到系统文件夹中
            }


            CAPTS_Borker.caseNumber = Mnumbers;//将设置参数赋值给软件静态函数
            CAPTS_Borker.T1 = Signle_Case_Time;//单次抽气时间
            CAPTS_Borker.T2 = Cycle_Case_Time;//抽气间隔时间
            CAPTS_Borker.T3 = Loop_Time;//循环间隔时间
            CAPTS_Borker.LoopCount = Loop_Count;//循环次数
                                                //设置箱子体积，温度压强等参数
            double Volume = Double.Parse(materialTextBox27.Text);
            double G_area = Double.Parse(materialTextBox3.Text);
            double Temperature = Double.Parse(materialTextBox5.Text);
            double Pressure = Double.Parse(materialTextBox2.Text);
            int Beigin_time = Convert.ToInt32(numericUpDown8.Value);
            int Log_time = Convert.ToInt32(numericUpDown9.Value);
            if (Beigin_time > Signle_Case_Time)
            {
                MessageBox.Show("警告：起始时间不得超过箱体测量时间");
            }
            if (Log_time > Signle_Case_Time - Beigin_time)
            {
                MessageBox.Show("警告：测量时间不得超过箱体测量时间减起始时间");
            }
            string str_PT = "PT:";
            string str1_PT = Volume.ToString() + "," + G_area.ToString() + "," + Temperature.ToString() + "," + Pressure.ToString() + "," + Beigin_time.ToString() + "," + Log_time.ToString();
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str_PT, str1_PT);//将设置文件保存到系统文件夹中
            string Pow_Time = "TIM:";
            string pow_on_off = dateTimePicker1.Text.ToString() + "," + dateTimePicker2.Text.ToString();
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, Pow_Time, pow_on_off);//将设置文件保存到系统文件夹中
            string Connect1 = "F:";
            string Is_connect1 = "1";
            if (materialCheckbox4.Checked)
            {
                Is_connect1 = "1";
            }
            else
            { Is_connect1 = "0"; }
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, Connect1, Is_connect1);
            string Slave_Setting = "SLA:";
            string Slave_text = comboBox2.Text.ToString() + "," + comboBox3.Text.ToString() + "," + comboBox4.Text.ToString() + "," + comboBox5.Text.ToString() + "," + comboBox6.Text.ToString()
                + "," + comboBox11.Text.ToString() + "," + comboBox10.Text.ToString() + "," + comboBox9.Text.ToString() + "," + comboBox8.Text.ToString() + "," + comboBox7.Text.ToString();
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, Slave_Setting, Slave_text);//将设置文件保存到系统文件夹中
            Setting.CHAMBER_VOLUMN = Volume;
            Setting.CHAMBER_GROUND_AREA = G_area;
            Setting.PRE_DELETE_TIME = Beigin_time;
            Setting.LOG_DURATION_CUTOFF = Log_time;

            string strc = "CO2:";
            string CO2_R = textBox12.Text + "," + textBox11.Text + "," + textBox10.Text + "," + textBox9.Text;
            //string CO2_R = textBox12.Text.PadLeft(8, '0') + textBox11.Text.PadLeft(8, '0') + textBox10.Text.PadLeft(8, '0') + textBox9.Text.PadLeft(8, '0');
            // CAPTS_Borker1.statusFlag(str1+CO2_R);
            //Thread.Sleep(10);
            string str2 = "H2O:";
            string H2O_R = textBox16.Text + "," + textBox15.Text + "," + textBox14.Text + "," + textBox13.Text;
            //string H2O_R =  textBox16.Text.PadLeft(8,'0') +  textBox15.Text.PadLeft(8, '0') + textBox14.Text.PadLeft(8, '0') + textBox13.Text.PadLeft(8, '0');
            //CAPTS_Borker1.statusFlag(str2+H2O_R);
            //Thread.Sleep(10);
            string str3 = "TEM:";
            string T_R = textBox20.Text + "," + textBox19.Text + "," + textBox18.Text + "," + textBox17.Text;
            //string T_R =  textBox20.Text.PadLeft(8, '0') +  textBox19.Text.PadLeft(8, '0') + textBox18.Text.PadLeft(8, '0') + textBox17.Text.PadLeft(8, '0');
            //CAPTS_Borker1.statusFlag(str3+T_R);
            //Thread.Sleep(10);
            string str4 = "RH:";
            string HR_R = textBox24.Text + "," + textBox23.Text + "," + textBox22.Text + "," + textBox21.Text;
            //string HR_R =  textBox24.Text.PadLeft(8, '0') + textBox23.Text.PadLeft(8, '0') + textBox22.Text.PadLeft(8, '0') + textBox21.Text.PadLeft(8, '0');
            // CAPTS_Borker1.statusFlag(str4+HR_R);
            //Thread.Sleep(10);
            string str5 = "PA:";
            string PA_R = textBox28.Text + "," + textBox27.Text + "," + textBox26.Text + "," + textBox25.Text;
            //string PA_R =  textBox28.Text.PadLeft(8, '0') + textBox27.Text.PadLeft(8, '0') + textBox26.Text.PadLeft(8, '0') + textBox25.Text.PadLeft(8, '0');
            // CAPTS_Borker1.statusFlag(PA_R+PA_R);
            // Thread.Sleep(10);
            string str6 = "PPFD:";
            string PPFD_R = textBox32.Text + "," + textBox31.Text + "," + textBox30.Text + "," + textBox29.Text;
            //string PPFD_R = textBox32.Text.PadLeft(8, '0') + textBox31.Text.PadLeft(8, '0') + textBox30.Text.PadLeft(8, '0') + textBox29.Text.PadLeft(8, '0');
            //CAPTS_Borker1.statusFlag(str6+PPFD_R);
            string str7 = "Light:";
            string light = textBox4.Text + "," + textBox3.Text + "," + textBox2.Text + "," + textBox1.Text;
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str7, light);//将设置文件保存到系统文件夹中
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, strc, CO2_R);
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str2, H2O_R);
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str3, T_R);
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str4, HR_R);
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str5, PA_R);
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str6, PPFD_R);
            MaterialSnackBar SnackBarMessage = new MaterialSnackBar("保存成功\r\n", "确认", true);
            SnackBarMessage.Show(this);
        }
        public void get_fittingdata(Series series, int case_ix, string selectedOption)
        {
            //获取对应显示数据

            List<string> CO2_S = new List<string>();
            List<string> H2O_S = new List<string>();
            List<string> CH4_S = new List<string>();
            List<string> N2O_S = new List<string>();
            List<string> NH3_S = new List<string>();
            List<String> case_num = new List<String>();
            foreach (var i in Fit_Data)
            {
                case_num.Add(i.Key);
                CO2_S.Add(Fit_Data[i.Key]["CO2slope"][case_ix]);
                H2O_S.Add(Fit_Data[i.Key]["H2Oslope"][case_ix]);
                CH4_S.Add(Fit_Data[i.Key]["CH4slope"][case_ix]);
                N2O_S.Add(Fit_Data[i.Key]["N2Oslope"][case_ix]);
                NH3_S.Add(Fit_Data[i.Key]["NH3_slope"][case_ix]);
            }
            //int i = Fit_Data[1][CO2_slope][0];
            switch (selectedOption)
            {
                case "CO₂Slope":
                    series.Points.Clear();
                    chart3.ChartAreas[0].AxisX.Interval = 1;
                    for (int i = 0; i < CO2_S.Count; i++)
                    {
                        series.Points.AddXY(case_num[i], CO2_S[i]);
                    }
                    chart3.ChartAreas[0].AxisX.Title = "测量箱序号"; // 设置X轴标题
                    break;
                case "H₂OSlope":
                    series.Points.Clear();
                    chart3.ChartAreas[0].AxisX.Interval = 1;
                    for (int i = 0; i < H2O_S.Count; i++)
                    {
                        series.Points.AddXY(case_num[i], H2O_S[i]);
                    }
                    chart3.ChartAreas[0].AxisX.Title = "测量箱序号"; // 设置X轴标题
                    break;
                case "CH₄Slope":
                    series.Points.Clear();
                    chart3.ChartAreas[0].AxisX.Interval = 1;
                    for (int i = 0; i < CH4_S.Count; i++)
                    {
                        series.Points.AddXY(case_num[i], CH4_S[i]);
                    }
                    chart3.ChartAreas[0].AxisX.Title = "测量箱序号"; // 设置X轴标题
                    break;
                case "N₂OSlope":
                    series.Points.Clear();
                    chart3.ChartAreas[0].AxisX.Interval = 1;
                    for (int i = 0; i < N2O_S.Count; i++)
                    {
                        series.Points.AddXY(case_num[i], N2O_S[i]);
                    }
                    chart3.ChartAreas[0].AxisX.Title = "测量箱序号"; // 设置X轴标题
                    break;
                case "NH₃Slope":
                    series.Points.Clear();
                    chart3.ChartAreas[0].AxisX.Interval = 1;
                    for (int i = 0; i < NH3_S.Count; i++)
                    {
                        series.Points.AddXY(case_num[i], NH3_S[i]);
                    }
                    chart3.ChartAreas[0].AxisX.Title = "测量箱序号"; // 设置X轴标题
                    break;
                default: break;
            }
        }

        public void get_fittingdata1(Series series, int case_ix, string selectedOption)
        {
            //获取对应显示数据

            List<string> CO2_S = new List<string>();
            List<string> H2O_S = new List<string>();
            List<string> CH4_S = new List<string>();
            List<string> N2O_S = new List<string>();
            List<string> NH3_S = new List<string>();
            List<String> case_num = new List<String>();
            foreach (var i in Fit_Data)
            {
                case_num.Add(i.Key);
                CO2_S.Add(Fit_Data[i.Key]["CO2slope"][case_ix]);
                H2O_S.Add(Fit_Data[i.Key]["H2Oslope"][case_ix]);
                CH4_S.Add(Fit_Data[i.Key]["CH4slope"][case_ix]);
                N2O_S.Add(Fit_Data[i.Key]["N2Oslope"][case_ix]);
                NH3_S.Add(Fit_Data[i.Key]["NH3_slope"][case_ix]);
            }
            //int i = Fit_Data[1][CO2_slope][0];
            switch (selectedOption)
            {
                case "CO₂Slope":
                    series.Points.Clear();
                    chart3.ChartAreas[0].AxisX.Interval = 1;
                    for (int i = 0; i < CO2_S.Count; i++)
                    {
                        series.Points.AddXY(case_num[i], CO2_S[i]);
                    }
                    chart3.ChartAreas[0].AxisX.Title = "测量箱序号"; // 设置X轴标题
                    break;
                case "H₂OSlope":
                    series.Points.Clear();
                    chart3.ChartAreas[0].AxisX.Interval = 1;
                    for (int i = 0; i < H2O_S.Count; i++)
                    {
                        series.Points.AddXY(case_num[i], H2O_S[i]);
                    }
                    chart3.ChartAreas[0].AxisX.Title = "测量箱序号"; // 设置X轴标题
                    break;
                case "CH₄Slope":
                    series.Points.Clear();
                    chart3.ChartAreas[0].AxisX.Interval = 1;
                    for (int i = 0; i < CH4_S.Count; i++)
                    {
                        series.Points.AddXY(case_num[i], CH4_S[i]);
                    }
                    chart3.ChartAreas[0].AxisX.Title = "测量箱序号"; // 设置X轴标题
                    break;
                case "N₂OSlope":
                    series.Points.Clear();
                    chart3.ChartAreas[0].AxisX.Interval = 1;
                    for (int i = 0; i < N2O_S.Count; i++)
                    {
                        series.Points.AddXY(case_num[i], N2O_S[i]);
                    }
                    chart3.ChartAreas[0].AxisX.Title = "测量箱序号"; // 设置X轴标题
                    break;
                case "NH₃Slope":
                    series.Points.Clear();
                    chart3.ChartAreas[0].AxisX.Interval = 1;
                    for (int i = 0; i < NH3_S.Count; i++)
                    {
                        series.Points.AddXY(case_num[i], NH3_S[i]);
                    }
                    chart3.ChartAreas[0].AxisX.Title = "测量箱序号"; // 设置X轴标题
                    break;
                default: break;
            }
        }
        private void materialButton2_Click(object sender, EventArgs e)
        {
            if (radioButton3.Checked)
            {
                Items_Slope = "CO₂Slope";
            }
            else if (radioButton4.Checked)
            {
                Items_Slope = "H₂OSlope";
            }
            else if (radioButton5.Checked)
            {
                Items_Slope = "CH₄Slope";
            }
            else if (radioButton6.Checked)
            {
                Items_Slope = "N₂OSlope";
            }
            else if (radioButton7.Checked)
            {
                Items_Slope = "NH₃Slope";
            }
            Series series = chart3.Series["柱状图"];
            get_fittingdata(series, combox_selectedIndex, Items_Slope);
        }

        private void materialButton62_Click(object sender, EventArgs e)
        {
            textBox6.Clear();
        }

        private void materialCheckbox2_CheckedChanged(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                materialCheckbox2.Text = "自定义模式-✅";
                previousCaseIndex = "1";
            }
            else
            {
                materialCheckbox2.Text = "自定义模式-❎";
            }
        }


        private void materialFloatingActionButton1_Click(object sender, EventArgs e)
        {
            if (materialFloatingActionButton1.Text == "暂停")
            {
                materialFloatingActionButton1.Icon = global::CAPTS.Properties.Resources.CarbonContinueFilled;
                CAPTS_Borker.LoopSate = false;//改变线程状态暂停线程
                CAPTS_Borker1.Set_Pump("KB", 0, CAPTS_Borker.Address1);// 发指令，关闭主机气泵
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Set_Pump("KB", 1, CAPTS_Borker.Address1)))
                {
                    MessageBox.Show("关闭主机气泵响应超时，请检查主机连接");
                }
                if (CAPTS_Borker.slave_runflag)
                {
                    CAPTS_Borker1.Set_Pump("KB", 0, CAPTS_Borker.Address2);// 发指令，关闭从机气泵
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Set_Pump("KB", 1, CAPTS_Borker.Address2)))
                    {
                        MessageBox.Show("关闭从机气路响应超时，请检从机连接");
                    }
                    slave_stop = true;
                }

                materialFloatingActionButton1.Text = "继续";
                materialCard2.Enabled = true;
                materialCard4.Enabled = true;
                CAPTS_Borker.Pro_State = "measureLoop Pause !!!";
                timer2.Stop(); // 暂停定时器
            }
            else if(materialFloatingActionButton1.Text == "继续")
            {

                materialFloatingActionButton1.Icon = global::CAPTS.Properties.Resources.MaterialSymbolsPause;
                CAPTS_Borker.LoopSate = true;//改变线程状态暂停线程
                CAPTS_Borker1.Set_Pump("KB", 1, CAPTS_Borker.Address1);// 发指令，打开主机气泵
                if (slave_stop)
                {
                    slave_stop = false;
                    CAPTS_Borker1.Set_Pump("KB", 0, CAPTS_Borker.Address2);// 发指令，打开从机气泵
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Set_Pump("KB", 1, CAPTS_Borker.Address2)))
                    {
                        MessageBox.Show("关闭从机气路响应超时，请检从机连接");
                    }
                }
                materialFloatingActionButton1.Text = "暂停";
                materialCard2.Enabled = false;
                materialCard4.Enabled = false;
                CAPTS_Borker.Pro_State = "measureLoop Run !!!";
                timer2.Start(); // 启动定时器
            }
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result = MessageBox.Show("确认退出系统吗？", "退出询问",
                                  MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            // 判断是否取消事件
            if (result == DialogResult.No)
            {
                // 取消退出
                e.Cancel = true;
                return; // 直接返回，无需继续执行
            }
            try
            {
                // 如果连接标志为 true，则尝试发送关闭命令
                if (connect_flag)
                {
                    CAPTS_Borker1.BroadCast("KY", 0); // 串口发送关闭
                }
            }
            catch (Exception ex)
            {
               // Console.WriteLine("关闭串口时发生错误: " + ex.Message);
            }
            finally
            {
                // 确保程序退出
                System.Environment.Exit(0);
            }
        }


        private void numericUpDown4_ValueChanged(object sender, EventArgs e)
        {
            if (Device_Flag.Equals("3"))
            {
                int sum_time = Convert.ToInt32(numericUpDown3.Value) * Convert.ToInt32(numericUpDown10.Value) + 600 + 45;
                numericUpDown6.Value = sum_time / 60;
                numericUpDown7.Value = sum_time % 60;
            }
            else
            {
                int Cycle_Case_Time = Convert.ToInt32(numericUpDown4.Value) * Convert.ToInt32(numericUpDown3.Value) + 10;
                numericUpDown1.Value = Cycle_Case_Time / 60;
                numericUpDown2.Value = Cycle_Case_Time % 60;
            }

        }

        private void numericUpDown3_ValueChanged(object sender, EventArgs e)
        {
            if (Device_Flag.Equals("3"))
            {
                int sum_time = Convert.ToInt32(numericUpDown3.Value) * Convert.ToInt32(numericUpDown10.Value) + 600 + 45;
                numericUpDown6.Value = sum_time / 60;
                numericUpDown7.Value = sum_time % 60;

            }
            else
            {
                int Single_Case_Time = Convert.ToInt32(numericUpDown4.Value) * Convert.ToInt32(numericUpDown3.Value) + 10;
                numericUpDown1.Value = Single_Case_Time / 60;
                numericUpDown2.Value = Single_Case_Time % 60;
            }

        }

        private void numericUpDown5_ValueChanged(object sender, EventArgs e)
        {
            if (Device_Flag.Equals("3"))
            {

            }
            else
            {
                int Single_Case_Time = Convert.ToInt32(numericUpDown4.Value) * Convert.ToInt32(numericUpDown3.Value) + 10;
                int Loop_Time = Convert.ToInt32(numericUpDown5.Value) * Single_Case_Time + 600;
                numericUpDown6.Value = Loop_Time / 60;
                numericUpDown7.Value = Loop_Time % 60;
            }

        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            if (Device_Flag.Equals("3"))
            {

            }
            else
            {
                int Single_Case_Time = Convert.ToInt32(numericUpDown4.Value) * Convert.ToInt32(numericUpDown3.Value) + 10;
                int Loop_Time = Convert.ToInt32(numericUpDown5.Value) * Single_Case_Time + 600;
                numericUpDown6.Value = Loop_Time / 60;
                numericUpDown7.Value = Loop_Time % 60;
            }

        }

        private void numericUpDown2_ValueChanged(object sender, EventArgs e)
        {
            if (Device_Flag.Equals("3"))
            {

            }
            else
            {
                int Single_Case_Time = Convert.ToInt32(numericUpDown4.Value) * Convert.ToInt32(numericUpDown3.Value) + 10;
                int Loop_Time = Convert.ToInt32(numericUpDown5.Value) * Single_Case_Time + 600;
                numericUpDown6.Value = Loop_Time / 60;
                numericUpDown7.Value = Loop_Time % 60;
            }

        }

        private void tabPage6_Click(object sender, EventArgs e)
        {
            numericUpDown3_ValueChanged(numericUpDown1, EventArgs.Empty);
            numericUpDown4_ValueChanged(numericUpDown1, EventArgs.Empty);
            numericUpDown5_ValueChanged(numericUpDown1, EventArgs.Empty);
        }

        private void materialButton56_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("1;");
            }
            else
            {
                if (materialButton56.Text == "1")
                {
                    CAPTS_Borker1.Send_Command("KX", 1);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 1)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton56.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 1);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 1)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton56.Text = "1";
                }
            }
        }

        private void materialButton55_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("2;");
            }
            else
            {
                if (materialButton55.Text == "2")
                {
                    CAPTS_Borker1.Send_Command("KX", 2);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 2)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton55.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 2);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 2)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton55.Text = "2";
                }
            }
        }

        private void materialButton54_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("3;");
            }
            else
            {
                if (materialButton54.Text == "3")
                {
                    CAPTS_Borker1.Send_Command("KX", 3);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 3)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton54.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 3);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 3)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton54.Text = "3";
                }
            }
        }

        private void materialButton53_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("4;");
            }
            else
            {
                if (materialButton53.Text == "4")
                {
                    CAPTS_Borker1.Send_Command("KX", 4);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 4)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton53.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 4);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 4)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton53.Text = "4";
                }
            }
        }

        private void materialButton52_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("5;");
            }
            else
            {
                if (materialButton52.Text == "5")
                {
                    CAPTS_Borker1.Send_Command("KX", 5);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 5)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton52.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 5);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 5)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton52.Text = "5";
                }
            }
        }

        private void materialButton51_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("6;");
            }
            else
            {
                if (materialButton51.Text == "6")
                {
                    CAPTS_Borker1.Send_Command("KX", 6);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 6)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton51.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 6);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 6)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton51.Text = "6";
                }
            }
        }

        private void materialButton50_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("7;");
            }
            else
            {
                if (materialButton50.Text == "7")
                {
                    CAPTS_Borker1.Send_Command("KX", 7);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 7)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton50.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 7);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 7)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton50.Text = "7";
                }
            }
        }

        private void materialButton49_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("8;");
            }
            else
            {
                if (materialButton49.Text == "8")
                {
                    CAPTS_Borker1.Send_Command("KX", 8);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 8)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton49.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 8);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 8)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton49.Text = "8";
                }
            }
        }

        private void materialButton48_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("9;");
            }
            else
            {
                if (materialButton48.Text == "9")
                {
                    CAPTS_Borker1.Send_Command("KX", 9);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 9)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton48.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 9);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 9)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton48.Text = "9";
                }
            }
        }

        private void materialButton47_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("10;");
            }
            else
            {
                if (materialButton47.Text == "10")
                {
                    CAPTS_Borker1.Send_Command("KX", 10);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 10)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton47.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 10);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 10)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton47.Text = "10";
                }
            }
        }

        private void materialButton46_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("11;");
            }
            else
            {
                if (materialButton46.Text == "11")
                {
                    CAPTS_Borker1.Send_Command("KX", 11);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 11)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton46.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 11);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 11)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton46.Text = "11";
                }
            }
        }

        private void materialButton45_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("12;");
            }
            else
            {
                if (materialButton45.Text == "12")
                {
                    CAPTS_Borker1.Send_Command("KX", 12);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 12)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton45.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 12);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 12)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton45.Text = "12";
                }
            }
        }

        private void materialButton44_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("13;");
            }
            else
            {
                if (materialButton44.Text == "13")
                {
                    CAPTS_Borker1.Send_Command("KX", 13);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 13)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton44.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 13);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 13)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton44.Text = "13";
                }
            }
        }

        private void materialButton43_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("14;");
            }
            else
            {
                if (materialButton43.Text == "14")
                {
                    CAPTS_Borker1.Send_Command("KX", 14);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 14)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton43.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 14);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 14)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton43.Text = "14";
                }
            }
        }

        private void materialButton42_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("15;");
            }
            else
            {
                if (materialButton42.Text == "15")
                {
                    CAPTS_Borker1.Send_Command("KX", 15);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 15)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton42.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 15);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 15)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton42.Text = "15";
                }
            }
        }

        private void materialButton41_Click_1(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("16;");
            }
            else
            {
                if (materialButton41.Text == "16")
                {
                    CAPTS_Borker1.Send_Command("KX", 16);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 16)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton41.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 16);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 16)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton41.Text = "16";
                }
            }
        }




        private void materialButton78_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("19;");
            }
            else
            {
                if (materialButton78.Text == "19")
                {
                    CAPTS_Borker1.Send_Command("KX", 19);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 19)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查从机连接");
                    }
                    materialButton78.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 19);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 19)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查从机连接");
                    }
                    materialButton78.Text = "19";
                }
            }
        }

        private void materialButton57_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("20;");
            }
            else
            {
                if (materialButton57.Text == "20")
                {
                    CAPTS_Borker1.Send_Command("KX", 20);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 20)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查从机连接");
                    }
                    materialButton57.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 20);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 20)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查从机连接");
                    }
                    materialButton57.Text = "20";
                }
            }
        }

        private void materialButton38_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("21;");
            }
            else
            {
                if (materialButton38.Text == "21")
                {
                    CAPTS_Borker1.Send_Command("KX", 21);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 21)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton38.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 21);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 21)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton38.Text = "21";
                }
            }
        }

        private void materialButton37_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("22;");
            }
            else
            {
                if (materialButton37.Text == "22")
                {
                    CAPTS_Borker1.Send_Command("KX", 22);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 22)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton37.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 22);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 22)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton37.Text = "22";
                }
            }
        }

        private void materialButton36_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("23;");
            }
            else
            {
                if (materialButton36.Text == "23")
                {
                    CAPTS_Borker1.Send_Command("KX", 23);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 23)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton36.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 23);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 23)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton36.Text = "23";
                }
            }
        }

        private void materialButton35_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("24;");
            }
            else
            {
                if (materialButton35.Text == "24")
                {
                    CAPTS_Borker1.Send_Command("KX", 24);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 24)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton35.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 24);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 24)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton35.Text = "24";
                }
            }
        }

        private void materialButton34_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("25;");
            }
            else
            {
                if (materialButton34.Text == "25")
                {
                    CAPTS_Borker1.Send_Command("KX", 25);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 25)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton34.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 25);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 25)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton34.Text = "25";
                }
            }
        }

        private void materialButton33_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("26;");
            }
            else
            {
                if (materialButton33.Text == "26")
                {
                    CAPTS_Borker1.Send_Command("KX", 26);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 26)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton33.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 26);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 26)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton33.Text = "26";
                }
            }
        }

        private void materialButton32_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("27;");
            }
            else
            {
                if (materialButton32.Text == "27")
                {
                    CAPTS_Borker1.Send_Command("KX", 27);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 27)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton32.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 27);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 27)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton32.Text = "27";
                }
            }
        }

        private void materialButton31_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("28;");
            }
            else
            {
                if (materialButton31.Text == "28")
                {
                    CAPTS_Borker1.Send_Command("KX", 28);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 28)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton31.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 28);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 28)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton31.Text = "28";
                }
            }
        }

        private void materialButton30_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("29;");
            }
            else
            {
                if (materialButton30.Text == "29")
                {
                    CAPTS_Borker1.Send_Command("KX", 29);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 29)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton30.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 29);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 29)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton30.Text = "29";
                }
            }
        }

        private void materialButton29_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("30;");
            }
            else
            {
                if (materialButton29.Text == "30")
                {
                    CAPTS_Borker1.Send_Command("KX", 30);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 30)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton29.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 30);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 30)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton29.Text = "30";
                }
            }
        }

        private void materialButton28_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("31;");
            }
            else
            {
                if (materialButton28.Text == "31")
                {
                    CAPTS_Borker1.Send_Command("KX", 31);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 31)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton28.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 31);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 31)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton28.Text = "31";
                }
            }
        }

        private void materialButton27_Click(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("32;");
            }
            else
            {
                if (materialButton27.Text == "32")
                {
                    CAPTS_Borker1.Send_Command("KX", 32);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 32)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton27.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 32);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 32)))
                    {
                        MessageBox.Show("从机响应超时，请检查从机连接");
                    }
                    materialButton27.Text = "32";
                }
            }
        }


        private void materialTabControl1_Enter(object sender, EventArgs e)
        {
            using (StreamReader sr = new StreamReader(CAPTS_Borker.SysParameter))//需要加标定文件到指定文件夹
            {
                string line;
                // 从文件读取并显示行，直到文件的末尾 
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.Contains("CO2:"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        textBox12.Text = str2[0]; textBox11.Text = str2[1]; textBox10.Text = str2[2]; textBox9.Text = str2[3];
                    }
                    if (line.Contains("H2O:"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        textBox16.Text = str2[0]; textBox15.Text = str2[1]; textBox14.Text = str2[2]; textBox13.Text = str2[3];
                    }
                    if (line.Contains("TEM:"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        textBox20.Text = str2[0]; textBox19.Text = str2[1]; textBox18.Text = str2[2]; textBox17.Text = str2[3];
                    }
                    if (line.Contains("RH:"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        textBox24.Text = str2[0]; textBox23.Text = str2[1]; textBox22.Text = str2[2]; textBox21.Text = str2[3];
                    }
                    if (line.Contains("PA:"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        textBox28.Text = str2[0]; textBox27.Text = str2[1]; textBox26.Text = str2[2]; textBox25.Text = str2[3];
                    }
                    if (line.Contains("Light:"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        textBox4.Text = str2[0]; textBox3.Text = str2[1]; textBox2.Text = str2[2]; textBox1.Text = str2[3];
                    }
                    if (line.Contains("PPFD:"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        textBox32.Text = str2[0]; textBox31.Text = str2[1]; textBox30.Text = str2[2]; textBox29.Text = str2[3];
                    }
                    if (line.Contains("K:"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        numericUpDown4.Value = Convert.ToInt32(str2[0]);//测量箱数
                        numericUpDown10.Value = Convert.ToInt32(str2[5]);//主机数
                        numericUpDown11.Value = Convert.ToInt32(str2[6]);
                        int min = Convert.ToInt32(str2[2]) / 60;
                        int sec = Convert.ToInt32(str2[2]) % 60;

                        int MIN = Convert.ToInt32(str2[3]) / 60;
                        int SEC = Convert.ToInt32(str2[3]) % 60;
                        numericUpDown1.Value = min;//抽气间隔时间
                        numericUpDown2.Value = sec;//抽气间隔时间
                        numericUpDown3.Value = Convert.ToInt32(str2[1]);//单次抽气时间

                        numericUpDown5.Value = Convert.ToInt32(str2[4]);//自定义循环次数
                        CAPTS_Borker.LoopCount = Convert.ToInt32(str2[4]);
                        numericUpDown6.Value = MIN;
                        numericUpDown7.Value = SEC;
                    }
                    // 检查行是否以 "TIM:" 开头
                    if (line.StartsWith("TIM:"))
                    {
                        // 从 "TIM:" 后获取时间部分
                        string timePart = line.Substring("TIM:".Length).Trim();

                        // 按照 ',' 分割时间部分
                        string[] times = timePart.Split(',');
                        // 处理每个时间字符串
                        if (times.Length == 2)
                        {
                            dateTimePicker1.Text = times[0].Trim();
                            dateTimePicker2.Text = times[1].Trim();
                        }
                    }
                    if (line.StartsWith("SLA:"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        comboBox2.Text = str2[0];
                        comboBox3.Text = str2[1];
                        comboBox4.Text = str2[2];
                        comboBox5.Text = str2[3];
                        comboBox6.Text = str2[4];
                        comboBox11.Text = str2[5];
                        comboBox10.Text = str2[6];
                        comboBox9.Text = str2[7];
                        comboBox8.Text = str2[8];
                        comboBox7.Text = str2[9];
                    }
                }
            }
        }

        private void materialButton6_Click(object sender, EventArgs e)
        {
            var builder = new StringBuilder("\t\t\t\t\t欢迎使用CAPTS-101:\r\n\n");
            builder.AppendFormat(" - 主界面下常用按钮有“连接”，“断开连接”，“开始”，“停止”以及暂停按钮，圆形按钮为暂停按钮。\n");
            builder.AppendFormat(" - 下方数字按键为手动控制箱子！\n");
            builder.AppendFormat(" -----------------------------------------------------------------------\n");
            builder.AppendFormat(" - 第一步: 进入设置页面进行系统配置。\n");
            builder.AppendFormat(" - 第二步: 选择合适分析器，并点击“连接”按钮。\n");
            builder.AppendFormat(" - 第三步: 配置完成后点击“开始”按钮，系统将默认顺序（1-2）进行一次测量运行。\n");
            builder.AppendFormat(" - 若想要按照指定顺序，请勾选下方自定义模式，并输入自定义序号，输入时可通过软键盘输入，也可通过下方数字按钮输入。\n");
            builder.AppendFormat(" -----------------------------------------------------------------------\n");
            builder.AppendFormat(" - 若发现管子中有水珠，可点击“干燥气路”按钮后再开始\n");
            builder.AppendFormat(" - 测量完成后，可去D:\\CAPTS_data！路径或U盘路径下查看数据。\n");
            builder.AppendFormat(" - 小提示 : 查看保存的数据时需停止运行系统，否则会因为文件被占用导致系统写入数据失败！\n");
            builder.AppendFormat(" - 常见问题: 若出现软件显示不全，请将Windows显示分辨率设置为100%。\n");
            builder.AppendFormat(" - 若遇到无法解决的问题请及时与我们联系！\n");
            var batchOperationResults = builder.ToString();
            var mresult = MaterialMessageBox.Show(batchOperationResults, "操作手册");
        }





        private void numericUpDown10_ValueChanged(object sender, EventArgs e)
        {
            numericUpDown4.Value = numericUpDown10.Value + numericUpDown11.Value;
        }

        private void numericUpDown11_ValueChanged(object sender, EventArgs e)
        {
            numericUpDown4.Value = numericUpDown10.Value + numericUpDown11.Value;
        }

        private void materialButton9_Click(object sender, EventArgs e)
        {
            var builder = new StringBuilder("\t\t\t\t\t欢迎使用温室气体测量系统（C-GHG）！:\r\n\n");
            builder.AppendFormat(" - “单箱体测量时间”：单箱体实际抽气测量时间，若设置为30s，代表每个箱体测量时间为30s\n");
            builder.AppendFormat(" - “循环次数”：系统测量的循环次数，1-16号箱测量完成为1个循环，若设置为4，表示从1-16号箱循环测量4次\n");
            builder.AppendFormat(" - “单次时间”：单次循环所花费的时间，1-16号箱依次测量完成一个循环的时间\n");
            builder.AppendFormat(" - “起始时间”：开始计算数据的起始时间，若设置为10，单箱体测量时间为30s，即从第10s开始计算，与测量时间搭配使用\n");
            builder.AppendFormat(" - “测量时间”：计算数据所需要的时间，若起始时间为10，测量时间为20，，即从第10s开始，计算20s的时间\n");
            builder.AppendFormat(" -----------------------------------------------------------------------\n");
            builder.AppendFormat(" - 若遇到无法解决的问题请及时与我们联系！\n");
            var batchOperationResults = builder.ToString();
            var mresult = MaterialMessageBox.Show(batchOperationResults, "操作手册");
        }

        void check_pump(object sender, EventArgs e)
        {
            stop_time++;//1s一次
            if (stop_time == 325)//20*16路都干燥好了
            {
                stop_time = 0;
                close_pump.Stop();
                materialButton25.Text = "干燥气路";
                MessageBox.Show("干燥完成");
                return; 
            }
            if (!Dryis_open)
            {
                if (NoDry1 == CAPTS_Borker.stc_mcu14)//到下一路了
                {
                    CAPTS_Borker1.Master_Command("KB", 1);//主机气泵
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Master_Command("KB", 1)))
                    {
                    }
                    Dryis_open = true;                   
                }
                else
                    return;

            }
            else
            {
                if (NoDry == CAPTS_Borker.stc_mcu14)
                {
                    if (CAPTS_Borker.MasterToSlave == 16)//此时关闭气泵不需要打开了
                    {
                        CAPTS_Borker1.Master_Command("KB", 0);//主机气泵
                        if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Master_Command("KB", 0)))
                        {
                        }
                        stop_time = 0;
                        materialButton25.Text = "干燥气路";
                        close_pump.Stop();
                    }
                    else
                    {
                        CAPTS_Borker1.Master_Command("KB", 0);//主机气泵
                        if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Master_Command("KB", 0)))
                        {
                        }
                        NoDry1 = "KJ:" + (CAPTS_Borker.MasterToSlave + 1).ToString();
                        Dryis_open = false;//已经关闭，等到下一路再打开气泵
                    }
                }
            }

        }
        private void materialButton25_Click(object sender, EventArgs e)
        {
            if(Device_Flag.Equals("3"))
            {
                if (materialButton25.Text == "干燥气路")
                {
                    CAPTS_Borker1.Master_Command("KL", 1);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Master_Command("KL", 1)))
                    {
                    }
                    materialButton25.Text = "结束干燥";
                }
                else 
                {
                    CAPTS_Borker1.Master_Command("KL", 0);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Master_Command("KL", 0)))
                    {
                    }
                    materialButton25.Text = "干燥气路";
                }
            }
            else
            {
                if (materialButton25.Text == "干燥气路")
                {
                    CAPTS_Borker1.Master_Command("KJ", 1);//干燥主机气路
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Master_Command("KJ", 1)))
                    {
                    }
                    if (CAPTS_Borker.slave_connect)
                    {
                        CAPTS_Borker1.Slave_Command("KJ", 1);//干燥从机气路
                        if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Slave_Command("KJ", 1)))
                        {
                        }
                        NoDry = "KJ:" + CAPTS_Borker.MasterToSlave.ToString();//不干燥的气路
                        stop_time = 0;
                        close_pump = new System.Windows.Forms.Timer();
                        close_pump.Interval = 1000; // 检查间隔为1秒
                        close_pump.Tick += check_pump;  //检测单片机工作是否正常
                        close_pump.Start();
                    }
                    materialButton25.Text = "结束干燥";
                }
                else
                {
                    CAPTS_Borker1.Master_Command("KJ", 0);//干燥主机气路
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Master_Command("KJ", 0)))
                    {
                    }
                    if (CAPTS_Borker.slave_connect)
                    {
                        CAPTS_Borker1.Slave_Command("KJ", 0);//干燥从机气路
                        if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Slave_Command("KJ", 0)))
                        {
                        }
                        stop_time = 0;
                        close_pump.Stop();
                    }
                    materialButton25.Text = "干燥气路";
                }
            }

        }

        private void materialButton26_Click(object sender, EventArgs e)
        {
            if (materialButton26.Text == "主机电磁阀打开")
            {
                CAPTS_Borker1.Set_Pump("KH", 1, CAPTS_Borker.Address1);// 发指令，打开主机123号电磁阀
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Set_Pump("KH", 1, CAPTS_Borker.Address1)))
                {
                    MessageBox.Show("打开主机气路响应超时，请检查主机连接");
                }
                materialButton26.Text = "主机电磁阀闭合";
            }
            else
            {

                CAPTS_Borker1.Set_Pump("KH", 0, CAPTS_Borker.Address1);// 发指令，闭合主机123号电磁阀
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Set_Pump("KH", 0, CAPTS_Borker.Address1)))
                {
                    MessageBox.Show("打开主机气路响应超时，请检查主机连接");
                }
                materialButton26.Text = "主机电磁阀打开";
            }
        }

        private void materialButton83_Click(object sender, EventArgs e)
        {
            if (materialButton83.Text == "从机电磁阀打开")
            {
                CAPTS_Borker1.Set_Pump("KH", 1, CAPTS_Borker.Address2);// 发指令，打开从机123号电磁阀
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Set_Pump("KH", 1, CAPTS_Borker.Address2)))
                {
                    MessageBox.Show("打开主机气路响应超时，请检查主机连接");
                }
                materialButton83.Text = "从机电磁阀闭合";
            }
            else
            {

                CAPTS_Borker1.Set_Pump("KH", 0, CAPTS_Borker.Address2);// 发指令，闭合从机123号电磁阀
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Set_Pump("KH", 0, CAPTS_Borker.Address2)))
                {
                    MessageBox.Show("打开主机气路响应超时，请检查主机连接");
                }
                materialButton83.Text = "从机电磁阀打开";
            }
        }

        private void materialRadioButton3_CheckedChanged(object sender, EventArgs e)
        {
            if (materialRadioButton3.Checked)
            {
                Device_Flag = "1";
            }
        }

        private void materialRadioButton7_CheckedChanged(object sender, EventArgs e)
        {
            if (materialRadioButton7.Checked)
            {
                Device_Flag = "2";
            }
        }

        private void materialRadioButton6_CheckedChanged(object sender, EventArgs e)
        {
            if (materialRadioButton6.Checked)
            {
                Device_Flag = "3";
            }
        }

        private void materialMultiLineTextBox22_Click(object sender, EventArgs e)
        {

        }

        private async void materialButton85_Click(object sender, EventArgs e)
        {
            // 解析光强梯度
            string gradientText = textBox5.Text.Trim();
            int[] intensities;
            try
            {
                intensities = gradientText.Split(' ')
                                          .Select(int.Parse)
                                          .ToArray();
            }
            catch
            {
                MessageBox.Show("光强梯度输入格式错误，请输入空格分隔的整数！");
                return;
            }

            // 获取适应时间和间隔时间
            if (!int.TryParse(materialTextBox4.Text, out int adaptTime) || adaptTime < 0)
            {
                MessageBox.Show("适应时间输入错误，请输入非负整数！");
                return;
            }

            if (!int.TryParse(materialTextBox7.Text, out int intervalTime) || intervalTime < 0)
            {
                MessageBox.Show("间隔时间输入错误，请输入非负整数！");
                return;
            }

            // 初始化取消令牌
            cts = new CancellationTokenSource();
            CancellationToken token = cts.Token;

            // 禁用按钮，防止重复点击
            materialButton85.Enabled = false;
            materialButton89.Enabled = true;

            adaptTime *= 1000;
            intervalTime *= 1000;

            // 初始化进度条
            materialProgressBar2.Maximum = intensities.Length;
            materialProgressBar2.Value = 0;

            int intensity = 0;

            try
            {
                // 遍历光强梯度数组
                for (int i = 0; i < intensities.Length; i++)
                {
                    // 如果 `materialButton89_Click` 触发取消，则提前终止
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }


                    if (materialCheckbox5.Checked)
                    {
                        if (light_d != 0)
                        {
                            intensity = Convert.ToInt32(Math.Round((light_a * intensities[i] + light_b - light_c) / light_d));
                            if (intensity < 0)
                            {
                                intensity = 0;
                            }
                            intensity = Convert.ToInt32(Math.Round((intensity / (double)light_max) * 255));
                        }
                        else
                        {
                            intensity = Convert.ToInt32(Math.Round((intensity / (double)light_max) * 255));
                        }
                    }
                    else
                    {
                        intensity = Convert.ToInt32(Math.Round((intensities[i] / (double)light_max) * 255));
                    }

                    CAPTS_Borker1.Master_Command("KN", intensity); // 发送指令

                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000,
                                                        () => CAPTS_Borker1.Master_Command("KN", intensity)))
                    {
                        // 这里可以添加额外的错误处理逻辑
                    }

                    materialTextBox1.Text = intensities[i].ToString();

                    // 更新进度条
                    Invoke(new Action(() => materialProgressBar2.Value = i + 1));

                    // 等待适应时间（第一个光强）或间隔时间
                    int waitTime = (i == 0) ? adaptTime : intervalTime;
                    await Task.Delay(waitTime, token); // 这里会检查 `token` 是否取消
                }
            }
            catch (TaskCanceledException)
            {
                
            }
            finally
            {
                // **任务完成或取消后，复原所有状态**
                ResetUI();
            }
        }

        private void materialButton86_Click(object sender, EventArgs e)
        {

            if (!int.TryParse(materialTextBox1.Text, out int intensity) || intensity < 0)
            {
                MessageBox.Show("总光量子密度输入错误，请输入非负整数！");
                return;
            }
            if (materialCheckbox5.Checked)
            {
                //Console.WriteLine((intensity / (double)light_max)*255);
                //A和D为零时主板传入的数据不需要校准
                if (light_d != 0)
                {
                    intensity = Convert.ToInt32(Math.Round((light_a * intensity + light_b - light_c) / light_d));
                    if (intensity < 0)
                    {
                        intensity = 0;
                    }

                    intensity = Convert.ToInt32(Math.Round((intensity / (double)light_max) * 255, MidpointRounding.AwayFromZero));
                }     
                else
                {
                    intensity = Convert.ToInt32(Math.Round((intensity / (double)light_max) * 255, MidpointRounding.AwayFromZero));
                }
            }
            else
            {
                intensity = Convert.ToInt32(Math.Round((intensity / (double)light_max) * 255, MidpointRounding.AwayFromZero));

            }
            Console.WriteLine(intensity);
            CAPTS_Borker1.Master_Command("KN", intensity);//主机气泵
            //if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Master_Command("KN", intensity)))
            //{
            //}
        }

        private void materialButton87_Click(object sender, EventArgs e)
        {

        }

        private void tabPage11_Enter(object sender, EventArgs e)
        {
            using (StreamReader sr = new StreamReader(CAPTS_Borker.SysParameter))//需要加标定文件到指定文件夹
            {
                string line;

                // 从文件读取并显示行，直到文件的末尾 
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.Contains("Light" + ":"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        light_a = float.Parse(str2[0]);
                        light_b = float.Parse(str2[1]);
                        light_c = float.Parse(str2[2]);
                        light_d = float.Parse(str2[3]);
                    }
                    if(line.Contains("MAX" + ":"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        light_max = int.Parse(str2[0]);
                        textBox7.Text = light_max.ToString();
                    }
                    if (line.Contains("PRE" + ":"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        materialTextBox4.Text = str2[0];
                    }
                    if (line.Contains("WAIT" + ":"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        materialTextBox7.Text = str2[0];
                    }
                    if (line.Contains("GRA" + ":"))
                    {
                        string[] str1 = line.Split(':');
                        string[] str2 = str1[1].Split(',');
                        textBox5.Text = string.Join(" ", str2); // 以空格拼接，符合写入格式
                    }
                    //Console.WriteLine(line);
                }

            }
        }

        private void materialButton87_Click_1(object sender, EventArgs e)
        {
            if (!int.TryParse(textBox7.Text, out int maxintensity) || maxintensity < 0)
            {
                MessageBox.Show("最大光强输入错误，请输入非负整数！");
                return;
            }
            string str = "MAX:";
            string value = maxintensity.ToString();
            light_max = Convert.ToInt32(value);
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str, value);//将设置文件保存到系统文件夹中
            MessageBox.Show($"输入参数 {light_max} 成功！");
        }

        private void materialButton88_Click(object sender, EventArgs e)
        {
            string str = "GRA:"; // 需要匹配的字符串
            string value;
            try
            {
                string gradientText = textBox5.Text.Trim(); // 获取文本框内容并去除首尾空格

                // 解析整数，并用逗号连接
                value = string.Join(",", gradientText.Split(' ')
                                                            .Where(s => !string.IsNullOrWhiteSpace(s)) // 过滤空字符串
                                                            .Select(int.Parse));
            }
            catch
            {
                MessageBox.Show("光强梯度输入格式错误，请输入空格分隔的整数！");
                return;
            }

            // 调用 WriteData 写入 SysParameter
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str, value);
            if (!int.TryParse(materialTextBox4.Text, out int PRE) || PRE < 0)
            {
                MessageBox.Show("适应时间输入错误，请输入非负整数！");
                return;
            }
            string str1 = "PRE:";
            string value1 = PRE.ToString();
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str1, value1);//将设置文件保存到系统文件夹中
            if (!int.TryParse(materialTextBox7.Text, out int WAIT) || WAIT < 0)
            {
                MessageBox.Show("间隔时间输入错误，请输入非负整数！");
                return;
            }
            string str2 = "WAIT:";
            string value2 = WAIT.ToString();
            CAPTS_Borker1.WriteData(CAPTS_Borker.SysParameter, str2, value2);//将设置文件保存到系统文件夹中
            MessageBox.Show("保存成功！");
        }

        private void materialButton89_Click(object sender, EventArgs e)
        {
            if (cts != null)
            {
                cts.Cancel(); // 触发取消
            }
        }
        // **复原 UI 状态**
        private void ResetUI()
        {
            Invoke(new Action(() =>
            {
                materialProgressBar2.Value = 0;   // 进度条归零
                materialTextBox1.Text = "";       // 清空文本框
                materialButton85.Enabled = true;  // 启用开始按钮
                materialButton89.Enabled = false; // 禁用停止按钮
                CAPTS_Borker1.Master_Command("KN", 0);//主机气泵
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Master_Command("KN", 0)))
                {
                }
                MessageBox.Show("操作已被用户提前终止！");
            }));

            cts?.Dispose();
            cts = null; // 释放取消令牌
        }

        private void materialTabSelector1_Click(object sender, EventArgs e)
        {

        }

        private void materialButton90_Click(object sender, EventArgs e)
        {
            if (materialButton90.Text == "Debug")
            {
                Debug_Button = true;
                materialButton90.Text = "Stop";
                textBox8.Visible = true;
            }
            else 
            {
                Debug_Button = false;
                materialButton90.Text = "Debug";
                textBox8.Visible = false;
            }
        }

        private void materialTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void numericUpDown6_ValueChanged(object sender, EventArgs e)
        {

        }

        private void numericUpDown7_ValueChanged(object sender, EventArgs e)
        {

        }

        private void materialLabel10_Click(object sender, EventArgs e)
        {

        }

        private void materialLabel4_Click(object sender, EventArgs e)
        {

        }

        private void materialLabel28_Click(object sender, EventArgs e)
        {

        }

        private void materialLabel29_Click(object sender, EventArgs e)
        {

        }

        private void materialLabel23_Click(object sender, EventArgs e)
        {

        }

        private void materialLabel22_Click(object sender, EventArgs e)
        {

        }

        private void materialLabel13_Click(object sender, EventArgs e)
        {

        }

        private void materialLabel5_Click(object sender, EventArgs e)
        {

        }

        private void numericUpDown8_ValueChanged(object sender, EventArgs e)
        {

        }

        private void numericUpDown9_ValueChanged(object sender, EventArgs e)
        {

        }

        private void materialLabel19_Click(object sender, EventArgs e)
        {

        }

        private void materialLabel16_Click(object sender, EventArgs e)
        {

        }

        private void chart1_Click(object sender, EventArgs e)
        {

        }

        private void materialButton84_Click(object sender, EventArgs e)
        {
            if (materialButton84.Text == "干燥主从机连接管")
            {
                CAPTS_Borker1.Master_Command("KB", 1);//主机气泵
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Master_Command("KB", 1)))
                {
                }
                CAPTS_Borker1.Send_Command("KV", CAPTS_Borker.MasterToSlave); // 打开主从机气路，MasterToSlave为连接端口
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KV", CAPTS_Borker.MasterToSlave))) { MessageBox.Show("打开主机气路响应超时，请检查主机连接"); }
                CAPTS_Borker1.Master_Command("KH", 0);//主机电磁阀闭合
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Master_Command("KH", 0)))
                {
                }

                CAPTS_Borker1.Slave_Command("KB", 1);//从机气泵
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Slave_Command("KB", 1)))
                {
                }
                

                CAPTS_Borker1.Slave_Command("KI", 1);//从机电磁阀2打开，13闭合
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Slave_Command("KI", 1)))
                {
                }
                CAPTS_Borker1.Send_Command("KV", 17); // 
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KV", 17))) { MessageBox.Show("打开主机气路响应超时，请检查主机连接"); }
                MaterialSnackBar SnackBarMessage = new MaterialSnackBar("启动成功\r\n", "确认", true);
                SnackBarMessage.Show(this);
                materialButton84.Text = "停止";
            }
            else
            {
                CAPTS_Borker1.Master_Command("KB", 0);//主机气泵
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Master_Command("KB", 0)))
                {
                }
                CAPTS_Borker1.Send_Command("KM", CAPTS_Borker.MasterToSlave); // 打开主从机气路，MasterToSlave为连接端口
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KM", CAPTS_Borker.MasterToSlave))) { MessageBox.Show("打开主机气路响应超时，请检查主机连接"); }
                CAPTS_Borker1.Slave_Command("KB", 0);//从机气泵
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14 != CAPTS_Borker.BakeData, 1000, () => CAPTS_Borker1.Slave_Command("KB", 0)))
                {
                }
                CAPTS_Borker1.Slave_Command("KI", 0);//从机电磁阀2打开，13闭合
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Slave_Command("KI", 0)))
                {
                }
                CAPTS_Borker1.Send_Command("KM", 17); // 打开主从机气路，MasterToSlave为连接端口
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KM", 17))) { MessageBox.Show("打开主机气路响应超时，请检查主机连接"); }
                materialButton84.Text = "干燥主从机连接管";
            }

        }

        private void materialButton81_Click(object sender, EventArgs e)
        {
            if (materialButton81.Text == "主机气泵")
            {
                CAPTS_Borker1.Set_Pump("KB", 1, CAPTS_Borker.Address1);
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Set_Pump("KB", 1, CAPTS_Borker.Address1)))
                {
                }
                materialButton81.Text = "关闭主机气泵";
            }
            else
            {
                CAPTS_Borker1.Set_Pump("KB", 0, CAPTS_Borker.Address1);
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Set_Pump("KB", 0, CAPTS_Borker.Address1)))
                {
                }
                materialButton81.Text = "主机气泵";
            }
        }

        private void materialButton82_Click(object sender, EventArgs e)
        {
            if (materialButton82.Text == "从机气泵")
            {
                CAPTS_Borker1.Set_Pump("KB", 1, CAPTS_Borker.Address2);
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Set_Pump("KB", 1, CAPTS_Borker.Address2)))
                {
                }
                materialButton82.Text = "关闭从机气泵";
            }
            else
            {
                CAPTS_Borker1.Set_Pump("KB", 0, CAPTS_Borker.Address2);
                if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14!= CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Set_Pump("KB", 0, CAPTS_Borker.Address2)))
                {
                }
                materialButton82.Text = "从机气泵";
            }
        }

        private void materialButton40_Click_2(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("17;");
            }
            else
            {
                if (materialButton40.Text == "17")
                {
                    CAPTS_Borker1.Send_Command("KX", 17);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 17)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查从机连接");
                    }
                    materialButton40.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 17);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 17)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查从机连接");
                    }
                    materialButton40.Text = "17";
                }
            }
        }

        private void materialButton39_Click_2(object sender, EventArgs e)
        {
            if (materialCheckbox2.Checked)
            {
                textBox6.AppendText("18;");
            }
            else
            {
                if (materialButton39.Text == "18")
                {
                    CAPTS_Borker1.Send_Command("KX", 18);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KX", 18)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton39.Text = "RUN";
                }
                else
                {
                    CAPTS_Borker1.Send_Command("KY", 18);
                    if (!CAPTS_Borker1.WaitForCondition(() => CAPTS_Borker.stc_mcu14_slave != CAPTS_Borker.BakeData, 5000, () => CAPTS_Borker1.Send_Command("KY", 18)))
                    {
                        MessageBox.Show("打开箱盖响应超时，请检查主机连接");
                    }
                    materialButton39.Text = "18";
                }
            }
        }


        private void materialSwitch8_CheckedChanged(object sender, EventArgs e)
        {
            DrawerShowIconsWhenHidden = materialSwitch8.Checked;
        }

        private void MaterialButton3_Click(object sender, EventArgs e)
        {
            var builder = new StringBuilder("Batch operation report:\n\n");
            var random = new Random();
            var result = 0;

            for (int i = 0; i < 200; i++)
            {
                result = random.Next(1000);

                if (result < 950)
                {
                    builder.AppendFormat(" - Task {0}: Operation completed sucessfully.\n", i);
                }
                else
                {
                    builder.AppendFormat(" - Task {0}: 欢迎使用温室气体测量系统（C-GHG）！.: {1}).\n", i, result);
                }
            }

            var batchOperationResults = builder.ToString();
            var mresult = MaterialMessageBox.Show(batchOperationResults, "Batch Operation");
        }

        private void materialSwitch9_CheckedChanged(object sender, EventArgs e)
        {
            DrawerAutoShow = materialSwitch9.Checked;
        }


        public int convertTime2sec(string timeStr)
        {  //GOOD
           // format of timeStr is: 00:01:43
            if (timeStr.Length == 8)
            {
                int hour = int.Parse(timeStr.Substring(0, 2));
                int minute = int.Parse(timeStr.Substring(3, 2));
                int second = int.Parse(timeStr.Substring(6, 2));
                if (hour >= 0 && hour <= 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
                { // check the data is a right time format. 
                    int timeSec = hour * 3600 + minute * 60 + second;
                    return timeSec;
                }
                else
                { // the data format is wrong, or the data is not a time. 
                    return -1;
                }

            }
            else
            {  // not the right format. 
                return -1;
            }

        }
        public int convertTime2secFromZero(string baseTimeStr, string timeStr)
        {
            int baseTimeSec = convertTime2sec(baseTimeStr);
            int timeSec = convertTime2sec(timeStr);

            if (baseTimeSec == -1 || timeSec == -1)
            {
                // If either time string is invalid, return -1.
                return -1;
            }

            return timeSec - baseTimeSec;
        }
    }
}
